Adding CheckBoxes in SharePoint GridView (SPGridView)

No.of Views2764
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 Feb 2010 00:02:56
Tag : SharePoint , Development and Programming
In this article, I am going to show how to add a checkboxes in SPGRidVIew. I will iterate through the SPGridView to find out the selected rows.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

In this article, I am going to show how to add a checkboxes in SPGRidVIew. I will iterate through the SPGridView to find out the selected rows.

Step 1

Create a SharePoint project by selecting Web Part template.

Image Loading

Choose trust level to Fully. Or in other words deploy into the GAC.

Image Loading

Step 2

Add a class to the Web Part project. Give this class any name. I am giving name here CheckBoxTemplate

Image Loading

 

a. Add the namespaceSystem.Web.UI
b. Implement the interface ITemplate
c. This class has been ListItemType properties; this will contain the item type.
d. This contains a string property which holds the column name.

CheckBoxTemplate.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI.HtmlControls; 
namespace AWebPart
{class CheckBoxTemplate:ITemplate
    {private ListItemType _itemType;private string _columnName;public CheckBoxTemplate(ListItemType itemType, string columnName)
        {
            _itemType = itemType;
            _columnName = columnName;
        }public void InstantiateIn(Control   container)
        {switch (_itemType)
            {case ListItemType.Header :
                    LiteralControl header = new LiteralControl();
                    header.Text = string.Format("<b>{0}</b>", _columnName);
                    container.Controls.Add(header);break;case ListItemType.Item :
                    CheckBox checkboxitem = new CheckBox();
                    checkboxitem.ID = "selectedTask";
                    checkboxitem.Visible = true;
                    container.Controls.Add(checkboxitem);
                    HtmlInputHidden taskIdItem = new HtmlInputHidden();
                    taskIdItem.ID = "taskIdItem";
                    container.Controls.Add(taskIdItem);break;default :break;
            }
        }
    }
}

Step 3

Create a class Author.cs. This class is simple entity class which is holding Author as entity.

Image Loading

Authors.cs

using System;
using System.Collections.Generic;
using System.Text;
            
namespace AWebPart
{publicclass Author
    {public string Name { get; set ;}public int NumberOfArticles { get; set; } 
    }
}

Step 4

Now code against Web Part.
1. This is having a button, when we will click button we will loop through the grid view and find out the entire selected row.
2. While creating a grid view, we are adding Template Field as column. This column will contain the checkbox

TemplateField selectTaskColumn = new TemplateField();
selectTaskColumn.HeaderText = "Select Task";
selectTaskColumn.ItemTemplate = new CheckBoxTemplate(ListItemType.Item, "Select Task");
grv.Columns.Add(selectTaskColumn);

3. This code will loop through the all rows of Grid View and find out the selected row. We are iterating through and concatening all the authors in a string.

for (int idx = 0; idx < gridviewwithcheckbox.Rows.Count; idx++)
{
        CheckBox selectCtl = (CheckBox)gridviewwithcheckbox.Rows[idx].FindControl("selectedTask");
        HtmlInputHidden taskIdCtl = (HtmlInputHidden)gridviewwithcheckbox.Rows[idx].FindControl("taskIdItem");if (selectCtl.Checked && taskIdCtl.Value != String.Empty)
        {//System.Windows.Forms.MessageBox.Show(taskIdCtl.Value.ToString());str = str + taskIdCtl.Value.ToString();
        }
}

WebPart1.cs

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Windows;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;
using System.Data;
using System.Web.UI.HtmlControls;
namespace AWebPart
{
    [Guid("00bc296d-8515-4d12-b876-82dc7861a8e1")]public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
    { 
        SPGridView gridviewwithcheckbox=null;public WebPart1()
        {
        }protected override void CreateChildControls()
        {base.CreateChildControls();
            Panel p1 = new Panel();this.Controls.Add(p1);
            gridviewwithcheckbox = new SPGridView();
            createGridViewWithCheckBox(ref  gridviewwithcheckbox);
            p1.Controls.Add(gridviewwithcheckbox);
            Button b1 = new Button();
            b1.Text = "Click Here For Selected Item To Display";
            p1.Controls.Add(b1);
            b1.Click += new EventHandler(b1_Click);          
        }void b1_Click(object sender, EventArgs e)
        {string str = string.Empty;string strjavascript = string.Empty ;for (int idx = 0; idx < gridviewwithcheckbox.Rows.Count; idx++)
            {
                CheckBox selectCtl = (CheckBox)gridviewwithcheckbox.Rows[idx].FindControl("selectedTask");
                HtmlInputHidden taskIdCtl = (HtmlInputHidden)gridviewwithcheckbox.Rows[idx].FindControl("taskIdItem");if (selectCtl.Checked && taskIdCtl.Value != String.Empty)
                {//System.Windows.Forms.MessageBox.Show(taskIdCtl.Value.ToString());str = str + taskIdCtl.Value.ToString();                  
                }
             }
            Page.RegisterStartupScript("a", strjavascript);
        }public List<Author> GetAuthorDetails()
        {try{
                List<Author> Authors  = new List<Author>()
            {new Author(){Name = "Praveen Masood",NumberOfArticles =200},new Author(){Name = "R Raveen ",NumberOfArticles = 500},new Author(){ Name ="Dhananjay Kumar",NumberOfArticles =85},new Author(){Name =" Mahesh Chand ",NumberOfArticles =600}
            };return Authors;
            }catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(ex.Message);return null;
            }           
        }public void createGridViewWithCheckBox(ref SPGridView grv)
        {try{// grv = new SPGridView();DataTable dt = new DataTable();
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("NArticles", typeof(int));
                DataRow row;foreach (Author author in GetAuthorDetails())
                {
                    row = dt.Rows.Add();
                    row["Name"] = author.Name;
                    row["NArticles"] = author.NumberOfArticles;
                }
                TemplateField selectTaskColumn = new TemplateField();
                selectTaskColumn.HeaderText = "Select Task";
                selectTaskColumn.ItemTemplate = new CheckBoxTemplate(ListItemType.Item, "Select Task");
                grv.Columns.Add(selectTaskColumn);
                SPBoundField field;
                field = new SPBoundField();
                field.HeaderText = "Name";
                field.DataField = "Name";
                grv.Columns.Add(field);
                field = new SPBoundField();
                field.HeaderText = "Number of Articles";
                field.DataField = "NArticles";
                grv.Columns.Add(field);
                grv.AutoGenerateColumns = false;
                grv.DataSource = dt.DefaultView;
                grv.DataBind();
            }catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }private void gridviewwithcheckbox_RowDataBound(object sender, GridViewRowEventArgs e)
        {if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HtmlInputHidden itemId = (HtmlInputHidden)e.Row.FindControl("taskIdItem");if (itemId != null)
                {
                    DataRowView data = (DataRowView)e.Row.DataItem;
                    itemId.Value = data["TaskId"].ToString();
                }
            }
        }
    }
}

Right click and deploy the web part to the sharepoint site.

Output

Image Loading

Conclusion

In this article , I shown How to add a checkbox in SPGridview. Thanks for reading.

 

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
By:lavleenDate Of Posted:8/20/2010 1:44:14 AM
adding checkboxes in sharepoint list having groupby enabled
hi, i also have a requirement wherein i need to show checkboxes in sharepoint list. but my list has group by enabled. does this approach work for a list having grouping?
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top