Wednesday 20 May 2009

Find the Row of a Control in a DataGrid in its Click Event

The Click Event in DataGrids has reared its ugly head again. A colleague of mine has spent hours searching the internet, and there doesn't seem to be a solution to this one. Using the control's ClientID or UniqueID properties will not work as the row does not have an id. The simple solution is use the control's NamingContainer property. If you go back through the hierarchy you can also get to the containing grid. To make life easier I wrote an extension method that also performs the cast to the desired container.
public static class ControlExtensions
{
public static TControl GetNamingContainer<TControl>(this Control control) where TControl : Control
{
var namingContainer = control.NamingContainer;
if (namingContainer == null)
{
return null;
}
if (namingContainer is TControl)
{
return (TControl)namingContainer;
}
return GetNamingContainer(namingContainer);
}
}

Get a control's row by calling the extension method.
protected void LatestCheckBox_CheckedChanged(object sender, EventArgs e)
{
var checkBox = (CheckBox)sender;
var row = checkBox.GetNamingContainer<DataGridItem>();

var control = row.FindControl("TestLabel");
if ((control != null) && (control is Label))
{
var label = (Label)control;
label.Text = checkBox.Checked ? "Checked" : "Not Checked";
}
}

No comments:

Post a Comment