Click here to Skip to main content
15,886,110 members
Articles / Web Development / ASP.NET
Article

Selecting multiple checkboxes in a DataGrid control

Rate me:
Please Sign up or sign in to vote.
4.62/5 (15 votes)
4 Aug 2004 113.4K   44  
How to select multiple checkboxes in a DataGrid control.

Introduction

In this article, I will explain how to select multiple checkboxes which are inside a DataGrid web server control.

C#
foreach(DataGridItem dgi in myGrid.Items) 
{ 
    CheckBox myCheckBox = (CheckBox)dgi.Cells[0].Controls[1];
    if(myCheckBox.Checked == true)
    {
        name+= myGrid.DataKeys[dgi.ItemIndex].ToString();
        name+=",";
    }
}

Explanation

In the code, myGrid refers to a DataGrid. All the code provided is placed inside the ItemCommand Event of the DataGrid control. First, we iterate through the DataGrid items using the foreach loop.

C#
foreach(DataGridItem dgi in myGrid.Items)

In the body of the foreach loop, we assign our newly created instance of CheckBox the value of the checkbox presented in the DataGrid control. Which in this case lies in the first column of the DataGrid.

C#
CheckBox myCheckBox = (CheckBox)dgi.Cells[0].Controls[1];

After that, we check that if the checkbox has been checked or not, using a simple if statement.

C#
if(myCheckBox.Checked == true)

Once we find out that the checkbox has been checked, we use the DataKeys property of the DataGrid control to get the appropriate value from the checked row. In this case, I have set the DataKeys property to name, getting name value in my string name variable.

C#
name+= myGrid.DataKeys[dgi.ItemIndex].ToString();

You should always assign some primary key value to the DataKeys collection so that you can always retrieve more data with that value.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
-- There are no messages in this forum --