Friday, April 17, 2009

ASP.NET: Accessing the GridView Row And Controls In It

There are some buttons in one of our ASP.NET project that are being directly generated from the sql query by spitting out html code. In grid view to show these buttons some fields are bound to the expression generating these buttons. The problem with these button was that we cannot set server side properties for them. Our developers had to set causevalidation = false for some of these button but they were unable to do so.

I thought of solving this issue by using a select command button changed to a templated field. However by changing a select button to a templated field it stops doing it function of selecting a grid row. To do that I planned to use the click event of this button and find this button in the grid by iterating over the rows, once found use that row index to select the row, which would trigger the selection change event. I implemented this idea as follows:


protected void Button1_Click1(object sender, EventArgs e)
{

for (int i = 0; i < GridViewBiz.Rows.Count; i++)
{
if (GridViewBiz.Rows[i].FindControl("Button1").Equals(sender))
{
GridViewBiz.Rows[i].RowState = DataControlRowState.Selected;
break;
}
}
}



For some unknown reason this code was unable to find the control, as the control that is sending the event is something different then all the buttons in all the rows of grid.

Frustrated by this I tried to find this kind of topic on the internet. I found an answer on http://forums.asp.net/t/1137287.aspx.

Using that I reimplemented the method in following way:


protected void Button1_Click1(object sender, EventArgs e)
{
Button btnMoreDetails = (Button)sender;
GridViewRow row = (GridViewRow)btnMoreDetails.NamingContainer;
row.RowState = DataControlRowState.Selected;
bringMoreDetails();
}


The key in above code is using the NamingContainer property which is ideal to find the row in a grid situation. We will now use this method for finding different IDs (primary keys) when a templated button (will be implemented) for an action would be clicked.

The method bringMoreDetails() is being called as changing the selection is not triggering GridView_SelectedIndexChanged event.

0 comments:

Post a Comment