Command Behind GridView ButtonField

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

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

<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, only the postback appears, but nothing happens. Who can help me here?

if necessary, the code is behind:

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

Thanks.

+6
source share
3 answers

You must use the RowCommand gridview event. Set commandArgument to your unique element. (By default, it passes the row 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 name // Now you have access to the gridviewrow. } } 

Alternatively, if you installed the DataKeyNames gridview, you can access it as follows:

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

The CommandName property does not determine the invocation method. To do this, you need to create a method associated with the command event of the control.
I don’t know too much about GridViews, I’m afraid, but I think the easiest way to do this is to select it in the design in Visual Studio, go to the properties, click on the "Events" button (looks like flash lightning) and double-click on the event Rowcommand This should automatically create a method associated with the command button event.
You can then use the GridViewCommandEventArgs parameter to access the CommandName, CommandArgument, and CommandSource properties to find out which buttom caused the event.

0
source

Just adding, I wrote and tried the exact same way, but the button still doesn't work ...

... it took some time until I realized that I forgot something that was OnRowCommand="<YourGridViewName>_RowCommand" inside the GridView element in the **. cs * file

0
source

Source: https://habr.com/ru/post/887819/


All Articles