Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Nico Avatar asked May 11 '11 11:05

Nico


People also ask

How to use ButtonField in GridView in asp net c#?

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.

How to add button in GridView in html?

To add these ButtonFields, click on the Edit Columns link from the GridView's smart tag, select the ButtonField field type from the list in the upper left and click the Add button. Move the two ButtonFields so that they appear as the first two GridView fields.


2 Answers

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);
like image 153
Kamyar Avatar answered Sep 22 '22 22:09

Kamyar


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

like image 30
farisfath25 Avatar answered Sep 21 '22 22:09

farisfath25