Finding a control in a GridView that is DataBound

23 03 2009

I have a GridView that is databound to my database via a data access layer. On the end of the grid view, I have added a check box:

<asp:CheckBox ID="chkError" runat="server" />

A user is able to select one or more check boxes on rows within the GridView, and click a button to delete the selected row. In order for them to be able to do this, I need to go through each row in the GridView, find which ones are selected, and call my method to delete the row/rows.

My main problem was encountered trying to find the check box! As it is created dynamically, the C# code cannot see it until runtime. I got it working using the following code:

foreach (GridViewRow row in grdErrorAlert.Rows)
CheckBox ErrorCheck = (CheckBox)row.FindControl("chkError");
if (ErrorCheck.Checked)
//Delete this row!

The important line of code is:

CheckBox ErrorCheck = (CheckBox)row.FindControl("chkError");

This looks in the current row of the GridView, and finds the control “chkError” that is on that row. It then casts it as a check box and assigns it to a new instance of the check box ErrorCheck.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: