Introduction
In this article, I will explain how to select multiple checkboxes which are inside a DataGrid
web server control.
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.
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
.
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.
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.
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.