views:

6185

answers:

5

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.

+2  A: 

The easiest way that I've found is to use the Command event over the Click event, and send the item ID as the command argument.

You could also loop over the rows in the GridView and compare the ImageButton in the row to the sender argument in your Click event.

bdukes
I do this all the time with GridView bindings. It is great!
Dillie-O
It works but it's absurd that RowCommand can't tell you what row fired the command.
Jamie Ide
+2  A: 

Insteading of looping through the rows u 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
}

Hope this helps you!!!

Hemanshu Bhojak
Sweet - this is more efficient - I'll integrate it.
Jeffrey
Changing my answer to this, since this is closer to the solution I actually implemented.I ended up setting the TabIndex value, and looked at that. How do you use "RowIndex"? is that a custom attribute?
Jeffrey
Awesome Answer!!!
Eric
+2  A: 

Cast the sender to an ImageButton then cast the image button's NamingContainer to a row:

VB:

Dim btn as ImageButton = CType(sender, ImageButton)

Dim row as GridViewRow = CType(btn.NamingContainer, GridViewRow)

C#:

ImageButton btn = (ImageButton)sender;

GridViewRow row = (GridViewRow)btn.NamingContainer;

good solution..........worked for me
Pankaj Kumar
+1  A: 

Would agree with bdukes that the simplest option is to use the CommandArgument. Bind your data's unique ID number into that property, then handle the _RowCommand event.

For example:

<asp:TemplateField >
    <HeaderStyle Width="20" />
    <ItemTemplate>
        <asp:ImageButton ImageUrl="images/icons/iCal.png" CommandArgument='<%# Eval("Event_ID") %>' ToolTip="iCal" runat="server" Height="18" Width="18" />
    </ItemTemplate>
</asp:TemplateField>


Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand

   e.CommandArgument    'use this value in whatever way you like

End Sub
A: 

This is very good trick. I have another trick also. You can try it...

 protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
            int rowindex = rowSelect.RowIndex;
         }
    }

It's a also good method.

Apoorva Pratap