views:

12586

answers:

5

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

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument=" ? ? ? " />
        </Columns>
</gridview>
A: 

I typically bind this data using the RowDatabound event with the GridView:

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}
Dillie-O
A: 

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>
Christopher Edwards
it's with Single Quote: CommandArgument='<%# Container.DataItemIndex %>'
balexandre
A: 

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {

Button b = (Button)e.CommandSource;
b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();

}

fARcRY
+7  A: 

Here is a very simple way...

<gridview>
  <Columns>    
    <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument='<%# Container.DataItemIndex %>' />
  </Columns>
</gridview>
George
For GridView, its DataItemIndex AND NOT ItemIndex. ItemIndex is for the Repeater
Tawani
Thanks, I made the edit.
George
I got the error "System.Web.UI.WebControls.ButtonField does not have a DataBinding event." when I tried. But the CommandArgument are set automatically to rowindex (see the answer from Rich).
joeriks
+1  A: 

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 );
    ...
}
Rich
Thanks! Worked great.
joeriks