Search This Blog

Tuesday, August 31, 2010

Get GridView Row and GridView Row Index on Click Event of Button in TemplateField

GridView Markup

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
           <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'
                  CommandArgument = "Button1"  OnClick = "Button1_Click" />

Now when the Button is clicked the Click event of the Button is executed.

Code Behind

protected void Button1_Click(object sender, EventArgs e)
    GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
    int index = gvRow.RowIndex;
You will notice I am type casting the sender parameter to get the reference of the GridView Row. The sender is the Button Control, thus the parent of the Button Control is the Cell and the parent of the Cell is the GridView Row.
Button ----------> GridView Cell ----------> GridView Row
The same applies to LinkButton and ImageButton.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.