Tuesday, March 4, 2008

Get GridViewRow's Index on button click

Below is a sample how to catch the rowindex of a gridview on button click located in a template column.

Here's the gridview:


<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
GridView1.DataSource=UsersAccess.Instance.SelectTable();
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
GridViewRow row=((Button)sender).Parent.Parent as GridViewRow;
//Now I have the rowIndex
//I can : GridView1.Rows[row].FindControl("");
Response.Write(row.RowIndex);
}


Best Regards
Bilal Shouman

4 comments:

Anonymous said...

Big thanks....
I've been searching for this too long time.
Regards

Unknown said...

Would be better for maintainability to use .NamingContainer instead of .Parent.Parent

Anonymous said...

gooooooooooooooooooooood

AZE said...

Thank you very much :)