Thursday, May 26, 2005
Finding Controls in a DataGrid
One neat thing to do when working with an ASP.NET DataGrid control is to put some controls (TextBoxes, Links, CheckBoxes, Validators, etc.) in the header and footer of the DataGrid. It is easy to add these things to the grid using a TemplateColumn. However, finding these controls is difficult in the code. Even if you add a control and give it a unique name that does not match the name in any data bounded row or anywhere else on your page, ASP.NET cannot provide the automatic hookup to the controls like it can with a normal TextBox or other control. This is probably because the control lives inside of the DataGrid and is not visible to the Page as a whole.
The secret to finding these controls is knowing where to look. For controls inside a bounded row (like when a row is in edit mode), it is easy to find the appropriate DataGridItem and then use the FindControl method. The problem is that the header and footer are not contained in the DataGrid's DataGridItemCollection. Instead, I have to look inside the rows of the table that the DataGrid uses to display the information. Basically, the method is this:
It seems, however, that you do not actually need to specify the column. Just finding a control inside the row will work. So, to get the control named "MyTextBox" out of the header, use the following:
The secret to finding these controls is knowing where to look. For controls inside a bounded row (like when a row is in edit mode), it is easy to find the appropriate DataGridItem and then use the FindControl method. The problem is that the header and footer are not contained in the DataGrid's DataGridItemCollection. Instead, I have to look inside the rows of the table that the DataGrid uses to display the information. Basically, the method is this:
MyDataGrid.Controls(0).Controls(row).Controls(col).FindControl("MyTextBox")This looks in the col-th column of the row-th row of the 0-th table of the DataGrid to find the textbox named MyTextBox. Remember that all indexing starts at 0. So, for the row, 0 means the header row, 1 through MyDataGrid.Items.Count are the data bounded rows, and MyDataGrid.Items.Count+1 is the footer.
It seems, however, that you do not actually need to specify the column. Just finding a control inside the row will work. So, to get the control named "MyTextBox" out of the header, use the following:
MyDataGrid.Controls(0).Controls(0).FindControl("MyTextBox")And to get the control named "MyTextBox" out of the footer, use the following:
MyDataGrid.Control(0).Controls(MyDataGrid.Items.Count+1).FindControl("MyTextBox")