Search code examples
c#.netasp.netgridviewbuttonfield

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" />

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.


Solution

  • 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);