Getting row index from ImageButton in GridView

I have a Gridview with ImageButtons added to a column through a template field. I connected the function to the "OnClick" event.

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

+5
source share
5 answers

Instead of looping through the lines, 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
}
+12
source

Send the sender to ImageButton, then move the NamingContainer image button to the line:

VB:

Dim btn as ImageButton = CType(sender, ImageButton)

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

FROM#:

ImageButton btn = (ImageButton)sender;

GridViewRow row = (GridViewRow)btn.NamingContainer;
+12
source

bdukes, CommandArgument. , _RowCommand.

:

<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
+3
source

The easiest way I've found is to use the Command Click event and send the element identifier as an argument to the command.

You can also iterate over the rows in the GridView and compare the ImageButton in the row with the argument senderin the Click event.

+2
source

This is a very good trick. I have one more trick. You may try...

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

This is also a good method.

+2
source

All Articles