Tuesday, September 21, 2010

Capturing Row Index in ASP.Net Grid View

Sometimes you need to perform certain action on a particular row of Gridview. For that you need to find row index of that row first and in order to capture the row index you need to call RowIndex property of GridViewRow class inside any event of a control present in that particular row.
Suppose you have modified some columns of Gridview in Edit mode to some combo boxes/ dropdown lists and you want to perform certain action on that particular row selected row. Then you need to call RowIndex Property using DropDownList class. Similarly other classes for different controls are available like, LinkButton, TextBox, etc.

Sample code:
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int i = row.RowIndex;
or
LinkButton ddl = (LinkButton)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int i = row.RowIndex;
or
LinkButton ddl = (LinkButton)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int i = row.RowIndex;

Some other method to do the same:
int i = this.GridViewName.SelectedIndex;
or
int i = Convert.ToInt32(GridViewName.DataKeys[row.RowIndex].Value);
or
i = Convert.ToInt32(GridViewName.DataKeys[e.RowIndex].Value);
i = GridViewName.Rows[e.RowIndex].FindControl("ControlName ");
But, here ‘e’ should of type GridViewCommandEventArgs and not of EventArgs.
void GridViewName_AnyEvent (Object sender, GridViewCommandEventArgs e)

No comments:

Post a Comment