dinotom
dinotom

Reputation: 5162

gridview button field

I have a gridview with a buttonfield. I want to update a table in my database and change the button image on button click. What is best event for that where i can access the row index as well? I have tried using the RowCommand event but cant access the row index from that event

Upvotes: 1

Views: 929

Answers (3)

codeandcloud
codeandcloud

Reputation: 55288

Instead of asp:ButtonField use asp:TemplateField and an asp:Button inside that. Set a CommandName say, MyCommand. Now inside the RowCommand event, do this

var clickedRow = (GridViewRow)((Button)sender).NamingContainer;
var clickedIndex = clickedRow.RowIndex;

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can try with this code - based on CommandArgument

void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    if(e.CommandName=="Test")
    {
      int index = Convert.ToInt32(e.CommandArgument);
      GridViewRow row = CustomersGridView.Rows[index];
    }
  }

Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx

Upvotes: 2

Luke Baughan
Luke Baughan

Reputation: 4686

I've just checked the docs here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

If you look at the "Note" section (below for convenience) you should be able to get the RowIndex from the CommandArguement property:

Note To determine the index of the row that raised the event, use the CommandArgument property of the event argument that is passed to the event. 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.

Upvotes: 0

Related Questions