ASP.NET GridView RowIndex As CommandArgument


How can you access and display the row index of a gridview item as the command argument in a buttonfield column button?

   <asp:ButtonField  ButtonType="Button" 
        CommandName="Edit" Text="Edit" Visible="True" 
        CommandArgument=" ? ? ? " />
8/8/2013 5:50:44 PM

Accepted Answer

Here is a very simple way:

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />
3/27/2014 7:53:17 PM

MSDN says that:

The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
    int rowIndex = Convert.ToInt32( e.CommandArgument );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow