C# ASP.NET – GridView : How to Use Checkbox in Gridview to Select Multiple Rows

2009-01-06
//
http://pagead2.googlesyndication.com/pagead/show_ads.js

I wanted to select multiple rows of the grid view using check boxes to select each row.

In this post I will discus how and what I did to achieve this goal…

I used a template column which holds a check box to select or de-select a row in the grid view.

Adding a Template Column:

There are several simple ways to add a template column/field to your grid view:

  1. Select your grid view and then click on the small task button (the small square button located to the top right corner of the grid view control) and select “Add New Column…” from the “GridView Tasks” box.
    1. Use “TemplateField” as the field type
    2. Provide a header text
    3. click ok
  2. Or… Select “Edit Columns…” from the “GridView Tasks” box and
    1. Select “TemplateField” from the “Available fields: ” section
    2. Click “Add” button
    3. Provide a header text in the “TemplateField properties: ” section
    4. click ok
  3. Or… Select “Columns” from the grid view properties and follow the steps described in the earlier method (2nd one)

Adding a Checkbox to the Template Column:

  1. Select “Edit Templates” from the “GridView Tasks” box. Then it will show you the inside of the template.
  2. Select “Item Template” from the “Display: ” drop down list.
  3. Drag and drop a check box in the item template area.
  4. Give an id as “chkid” for the check box – You can use a different name if you want but make sure you don’t confuse when I use this name in later parts of this article.
  5. Click “End Template Editing” from the “GridView Tasks” box.

If you have completed the above steps correctly, you should see the expected checkbox column added in to the grid view.

Design View
As you can see in the image above, in my example I use a Name column along with the check box column to make this clearer.

How to Databind the Template Field:

I use a datatable to populate the gridview so we have to databind our two columns.

The second column name is a “BoundField” so to databind it simply specify the name of the data table column you want to bind to this column in “DataField” property under “Data” property set in the fields dialog box you get when adding the second column (use one of the ways I described above to add a column).

Databinding the template field is a bit tricky, but not hard.

  1. Click “Edit Templates” from the “GridView Tasks” box so that you will see the check box.
  2. Click on the small button with a triangle in the upper right corner of the check box which is similar to the one we clicked on the grid view to get the “Checkbox Tasks” box and then click on the “Edit Databindings…” link inside that box.

You can use this dialog box to bind any property of the control to a data source column

In this example we will bind the “Checked” property of our check box to a Boolean column called “Selected” of the data source.

For that:

  • Select “Checked” from the Bindable Properties section and enter following in the Custom Binding section:
    • DataBinder.Eval(Container, “DataItem.Selected“)
  • Note: the word “Selected” (in red color) refers to the “Selected” field of the data source.

Populating the GridView:

As I described earlier I create a simple data table in the page load, populate it with some dummy data and then bind the grid view with it.

Note: I have used several methods to add data to a table to illustrate those to you.

The Code:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", System.Type.GetType("System.Boolean")));
dt.Columns.Add(new DataColumn("Name", System.Type.GetType("System.String")));

DataRow dr = dt.NewRow();
dr.ItemArray = new object[] { false, "Cassian" };
dt.Rows.Add(dr);
dt.Rows.Add(new object[] { false, "Menol" });
dt.Rows.Add(new object[] { false, "Razeek" });

this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}

There are several things that I’d like to bring to your notice:

  • I have checked for postback to make sure this data population is not occurred in general post backs. The reason is the framework refreshes when the grid view is re-bound.
  • So if we don’t do this check, whenever we click on a check box, a postback occurs, the grid gets refreshed, the check boxes get cleared, we cannot keep track of what check boxes are selected…!
  • As illustrate in my code, you can either first populate a datarow and then add it to the datatable
  • Or you can directly add the items using only one line of code.

Retrieving the Status of Checkboxes:

Now we have completed the interface and the user now can select several rows of the grid view using the appropriate check box.

The next step is to capture the rows that the user has selected.

In my example, I have used a button, once clicked; it will display the list of names of the selected people.

I will introduce the code first and then explain it to you.

protected void Button1_Click(object sender, EventArgs e)
{
ArrayList names = new ArrayList();
foreach (GridViewRow gvr in this.GridView1.Rows)
{
if (((CheckBox)gvr.FindControl("chkid")).Checked == true)
{
names.Add(gvr.Cells[1].Text);
}
}

this.Label1.Text = string.Empty;
foreach (object itm in names)
{
this.Label1.Text += " " + itm.ToString();
}
}

Note following:

  • The code iterates through each row of the grid view using a for each loop, takes the Name field from the selected rows and then adds those names into a arraylist
  • The GridViewRow refers to a single row in a grid view
  • Control Control.FindControl(string controlID) – GridViewRow class provides this method to find a specific control within a grid view row. This method becomes very handy in situations like this where we cannot directly access the control from the code because those are generated at run time
  • FindControl returns a control so you have to explicitly cast the returned control to the type of it

Screen Shot:

21

Conclusion:

We can use a template field with a checkbox to allow user to select multiple rows using checkboxes associated to each row. When the button is clicked, checkbox of each row is checked for its status and the row is selected if the user has chosen it.

//
http://pagead2.googlesyndication.com/pagead/show_ads.js

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek

21 thoughts on “C# ASP.NET – GridView : How to Use Checkbox in Gridview to Select Multiple Rows

  1. Hi menol..I m a beginner for asp .net programming..your article really helped me and saved a lot of time for me..Good work..!

    Like

  2. how to fatch record from database which record i selected from datagridview using checkbox and that record i want to redirect on next page.

    Like

  3. To Maduri,

    You want to fetch more details from the database depending on the selected record from the gridview and you want to forward that details to the next screen. If this is the scenario you want to get done…

    First you can get the details you want from selected rows in the gridview by

    1 Iterating through the gridview
    2 Identify the checked rows
    3 Extract data you want by referring to cells in selected rows

    Then you have to query the database to fetch records you want by including the details you extracted from the gridview into the SQL query.

    Then if you want to take those details into a next page, I recommend you to store those data in the session so you can use it from any page you want.

    I hope this helped you.

    If what you want is different from this, Please write your scenario so I can try to help you better.

    Regards,
    Menol

    Like

  4. Hi Menol,

    I need the same source code along with paging,Without paging everything works fine but with paging i want save all the records selected with the checkbox in the grid to the database. Can you please help me out with that example.I have kept them in session for maintaining the states of checkboxes while paging but when we click submit all the selected check boxes accross pages need to be stored into database.

    Thanks,
    Bhanu Ananthoju.

    Like

  5. hello sir,
    i read your artical, its damm good. but i need more functionality, like, i want to deselect the header checkbox , when any one of the checkbox is deselect, and also i want to select again the header checkbox, when all the checkboxes are selected.
    Thanx in advance…..

    Like

  6. hello…
    can we do this dynamically?i.e.
    i get all tables from my database (SQL 2005) and i put them now in data tables (it a dataset)
    now how we can dynamically show these tables in a gridviews with checkboxes (each table has it’s own gridview)

    Like

  7. what is the mistake?
    using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    CheckBox ch;
    for (i = 0; i < GridView.Rows.Count; i++)
    {
    ch = GridView1.Rows[i].FindControl(“chk”);

    if(ch.Checked==true)
    {
    Response.Write(ch.Text + “”);
    }
    }
    }
    }

    Like

  8. hi menol, i have a problem when i want to insert the check box column(which is selected by user) in the grid view into the database .my code looks like:-
    —————————————————————

    protected void Button1_Click(object sender, EventArgs e)
    {

    ArrayList names = new ArrayList();
    foreach (GridViewRow gvr in this.GridView1.Rows)
    {
    if (((CheckBox)gvr.FindControl(“c”)).Checked == true)
    {
    names.Add( gvr.Cells[0].Text);

    }
    }

    //this.Label2.Text = string.Empty;
    foreach (object itm in names)
    {
    this.Label2.Text +=itm.ToString();
    SqlDataAdapter dal = new SqlDataAdapter(“select projectid from tblproject where projectname='”+itm.ToString()+”‘ “, abhiconnectionstring);
    DataSet ds = new DataSet();
    dal.Fill(ds);
    int s = int.Parse(ds.Tables[0].Rows[0][0].ToString());

    abhiconnectionstring.Open();
    SqlCommand cmd = new SqlCommand(“insert into tbltechskill (personid,projectid) values(‘” + TextBox3.Text.ToString() + “‘,'” +s+ “‘) “, abhiconnectionstring);
    cmd.ExecuteNonQuery();
    abhiconnectionstring.Close();
    // Response.Redirect(“project.aspx”);
    }
    ————————————————————but the problem is , selected checkbox value are not coming into the object itm i.e (itm.string()) ……….can you please help me

    Like

  9. hey menol… what to do if one wants to create checkbox with integer values not bool values? it shows error on browser…
    pls suggest something….. 🙂

    Like

  10. Very informative post. It’s really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Populate Grid Control From XML Document Easily, for more details of this post check out this link…

    http://mindstick.com/Articles/6c3ccf8c-6656-4a48-bfb7-e0221569de67/?Populate%20Grid%20Control%20From%20XML%20Document%20Easily

    Thanks Everyone!!

    Like

  11. HI,

    Why you can try.

    Generating button for each row as like check box, its show be different and interesting

    Like

  12. Thanks everyone for your comments!

    Unfortunately, I have to close comments to this post to reduce Spam comments.

    Like

Comments are closed.