ASP.Net GridView Checkbox Value using C#
ASP.Net GridView Checkbox value can be accessed using the same method that we discussed in the previous tutorial of ASP.Net GridView FindControl Checkbox. FindControl function returns the server control object as a naming container of server control. This same FindControl function can be used to access the server controls and their values placed inside the ASP.Net GridView Columns. The only difference is control type casting is required to access the relevant properties associates with any particular ASP.Net server control. For example Checked property value of checkbox that we will discuss in this tutorial. You can access the current state value of checkbox placed inside the ASP.Net GridView control using FindControl function. GridViewRow Class enables you to access the instance of a particular row and its Cells (Columns). You can access any particular cell by passing the number value such as 0, 1 or 2 to access 1st, 2nd or 3rd column within the limit of number of columns in each row. If there are 3 columns in each row of GridView then you can access each cell by passing 0 for 1st column, 1 for 2nd column and 2 for 3rd column.
GridView Examples:
You can see the live samples and examples of GridView from the following links:
C# Code to Access ASP.Net GridView Checkbox Value
CheckBox chk;
foreach (GridViewRow rowItem in GridView1.Rows)
{
// FindControl function gets the control placed inside the GridView control from the specified cell
// FindControl fucntion accepts string id of the control that you want to access
// type casting of control allows to access the properties of that particular control
// here checkbox control type cast is used to access its properties
chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));
// chk.checked will access the checkbox state value (on button click event)
if (chk.Checked)
{
Response.Write( GridView1.DataKeys[rowItem.RowIndex ]["CategoryID"].ToString() + "<br />");
}
}
Above C# code shows how to find checkbox control placed inside the ASP.Net GridView column and access its checked property value by type casting the control object returned by the FindControl function. You can also access the other database values for that particular row having checkbox checked state equal to true. In the above example code GridView DataKeys collection has been used to access the "categoryID" value representing the unique value for each GridView row items. If condition has been used here to test the value of checked property of checkbox in each row of GridView and shows the "categoryID" as output result on the web page for which it returns true.
Note: Categories table of SQL Northwind database has been used in the sample code to bind the data with GridView control.
In the next tutorial: ASP.Net C# GridView FindControl Checkbox you will learn how to find checkbox control placed inside the GridView control.
