Tuesday, March 18, 2008

How to get the current row in Gridview RowCommand event

Blogger Tags:

I've been working in a project where we use the Gridview control very often.

In this particularly case I need to get a reference to the current row of a gridview, in order to get some values that exists in several columns of the same gridview.

If we take a look at the signature of the method:

protected void GridView\_RowCommand(object sender, GridViewCommandEventArgs e)

you will notice that, at a first approach, in none of the parameters, we can get a reference to the current row.

Using the following single line of code, we can get a GridViewRow object referencing the current row.

GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;

The code above is not so elegant as I wish, but the world is not perfect as well. :)

We can now use the following code to get a reference to existing controls on the current GridView row.

DropDownList ddlPriority = row.FindControl("ddlPriority") as DropDownList;

int priorityID = ddlPriority != null ? Int32.Parse(ddlPriority.SelectedValue) : 0;


Problem fixed !!!