Getting row index from an ImageButton click in a GridView

Jeffrey picture Jeffrey · Jan 21, 2009 · Viewed 64.8k times · Source

I have a Gridview with ImageButtons added to a column via a templatefield. I've attached a function to the "OnClick" event.

Once in this function, how can I get the index of the row that has the button that has been clicked. It appears that all I have is the mouse coordinates on the page.

Answer

Hemanshu Bhojak picture Hemanshu Bhojak · Jan 21, 2009

Instead of looping through the rows you can use this

<asp:ImageButton runat="server" id="ibtn1" ... RowIndex='<%# Container.DisplayIndex %>' 
OnClick="button_click"/>

...

protected void button_click(object sender, EventArgs e){
    ImageButton ibtn1 = sender as ImageButton;
    int rowIndex = Convert.ToInt32(ibtn1.Attributes["RowIndex"]);

    //Use this rowIndex in your code
}