Wednesday, August 11, 2010

Finding Row Index in GridView RowCommand Event

GridView RowCommand Event


The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.

The GridView control also raises other specialized events when certain buttons are clicked; means buttons with the CommandName property set to "Delete", "Update", "Page" etc…

When using one of these buttons, you should consider handling one of the specialized events provided by the control; such as RowDeleted or RowDeleting.

We will discuss more about these specialized events later.

protected void gvProjects_RowCommand(object sender, GridViewCommandEventArgs e)
{


}

The above example shows a sample RowCommand event handling method.

A GridViewCommandEventArgs object is passed to the event-handling method, which allows you to determine the command name and command argument of the button clicked. To determine the command name and command argument, use the CommandName and CommandArgument properties, respectively. You can also access the button control that raised the event by using the CommandSource property.

To find index of row, which caused this event, we can use any of the following method:

1. We can use e.CommandArgument property to find row index. ( It will work only if we didn’t set the CommandArgument property of button which we clicked)

Eg:
int index = Convert.ToInt32(e.CommandArgument);

2. Second way is, we can find index from e.CommandSource property. See the following example to know more about it

Eg:
LinkButton lbtn = (LinkButton)e.CommandSource; // get event caused button
GridViewRow gvrow = (GridViewRow)lbtn.NamingContainer; // get grid row contains event caused button
int index = gvrow.RowIndex;


Hope It will help you to handle GridView's RowCommand Event.

No comments: