Tuesday, October 31, 2006

Accessing GridView's DataControlFieldCell Programmatically

How would you access the auto-generated control in the HyperLinkField (HyperLink control) and ButtonField (LinkButton or Button control) in RowDataBound event ? You will find out that FindControl() method would no longer be working since there is no concrete ID is assigned to the control, and you are not intelligent enough to know what ID will be assigned automatically by the compiler. There are two workarounds, in which the second one is new in ASP.NET 2.0.

Assuming that the HyperLinkField is at 4th column.

First Workaround

protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = e.Row.Cells[3].Controls[0] as HyperLink;
hl.Text = "Changing Text here";
}
}

This workaround is pretty straightward. Cells[3] refers to 4th column (index starting from 0) ; Controls[0] means the first control in that column, which is HyperLink control.

The first workaround is apparently classic way that we used in DataGrid control. But here is the another workaround, which works in different way !


Second Workaround

protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataControlFieldCell dField = e.Row.Cells[3] as
DataControlFieldCell;
HyperLinkField hlf = dField.ContainingField as HyperLinkField;
hlf.Text = "Changing Text here";
hlf.DataNavigateUrlFormatString = "nextpage.aspx?id={0}";
}
}

As you can see, I am accessing the HyperLinkField itself, and I am able to assign the DataNavigateUrlFormatString property in the RowDataBound event too. Of course, if you would like to access the control in that field, it can be done by

HyperLink hl = dField.Controls[0] as HyperLink;



Hope this helps...

No comments: