开发者

Command behind a GridView ButtonField

I got a question about the command behind a ButtonField (image type) in a GridView.

Got a GridView called gvIngevuld in wich I show rows of data and 1 ButtonField row. Now I have to put code behind these buttons (Each of them the same) to put some things in PDF format. The problem is I don't know how to put code behind these buttons ? The code I have :

<asp:ButtonField ButtonType="Image" ImageUrl="~/Images/pdf.png"  CommandName="pdf_click" /&g开发者_如何学编程t;

As you can see I used the CommandName="pdf_click" property but when I click one of the buttons there's only a postback but nothing happens. Anyone who can help me out here ?

in case needed, code behind :

protected void pdf_click(object sender, EventArgs e)
{
    lblWelkom.Text = "Succes!";
}

Thanks.


You should use RowCommand event of gridview. Set the commandArgument to your item's unique key. (By default, it passes the row's index)

void gvIngevuld_RowCommand(Object sender, GridViewCommandEventArgs e)
 {
 // If multiple buttons are used in a GridView control, use the
 // CommandName property to determine which button was clicked.
 if(e.CommandName=="pdf_click")
  {
   // Convert the row index stored in the CommandArgument
   // property to an Integer.
   int index = Convert.ToInt32(e.CommandArgument);

   // Retrieve the row that contains the button clicked 
   // by the user from the Rows collection.
   GridViewRow row = gvIngevuld.Rows[index]; 
   //gbIngevuld is your GridView's name

   // Now you have access to the gridviewrow.
  }  
}   

Also, If you have set the DataKeyNames of the gridview, you can access it as follows:

    int index = Convert.ToInt32(e.CommandArgument);
    int ServerID = Convert.ToInt32(GridView1.DataKeys[index].Value);


Just an addition, I wrote and tried exactly the same however the button still not working...

...it took some time till I realise that I forgot a thing, which was OnRowCommand="<YourGridViewName>_RowCommand" inside your GridView element in the **.cs* file


The CommandName property does not define the method to call. For that you need to create a method that is bound to the command event of the control.
I don't know too much about about GridViews i'm afraid but I would think the easiest way to do this would be to select it in design view in Visual Studio, go to properties, click on the events button (looks like a lightning flash) and double click on the RowCommand event propety. This should automatically create a method that is bound to a command button event.
You can then use the GridViewCommandEventArgs parameter to access the CommandName, CommandArgument and CommandSource properties to work out which buttom caused the event to fire.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜