Adding CheckBoxes in SharePoint GridView (SPGridView)



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.  

fig1.gif

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

 fig2.gif

Step 2

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

fig3.gif

  1. Add the namespace  System.Web.UI
  2. Implement the interface ITemplate
  3. This class has been ListItemType properties; this will contain the item type.
  4. 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. 

fig4.gif
 
Authors.cs

using
System;
using System.Collections.Generic;
using System.Text;

            

namespace AWebPart

{

    public  class 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

fig5.gif

Conclusion

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

Up Next
    Ebook Download
    View all
    Learn
    View all