0
How to: Respond to Button Events in a GridView Control
Posted by Rajendra Prasad Panchati
on
Friday, June 11, 2010
When a button is clicked in a GridView control, the RowCommand() event is raised. The GridView control has built-in functionality for operations such as edit, delete, and paging. You can also add buttons and use the RowCommand()event to add custom functionality to the control.
You can add custom functionality to a GridView control in the following ways:
You can add custom functionality to a GridView control in the following ways:
- By adding a ButtonField field to the GridView control.
- By adding a Button, LinkButton, or ImageButton controls to a template in the GridView control.
To respond to button events in the GridView control
- Set the button's CommandName property to a string that identifies its function, such as "Print" or "Copy".
- If you are using the TemplateField object and have to access the row index in the event handler method, set the button's CommandArgument property to an expression that identifies the current row.
The following example shows how you can set the CommandArgument property of a button in a TemplateFieldcolumn to the current row index. In the example, the column contains a Button control that displays a shopping cart.
- Create a method for the RowCommand() event of the GridView control. In the method, do the following:
- Check the CommandName property of the event-argument object to see what string was passed.
- Retrieve the index of the row that contains the button by using the CommandArgument property, if required.
- Perform the appropriate logic for the button that the user clicked.
For an example that uses the ButtonField class, see the GridViewRowCommand() event documentation.protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "AddToCart") { // Retrieve the row index stored in the // CommandArgument property. int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button // from the Rows collection. GridViewRow row = GridView1.Rows[index]; // Add code here to add the item to the shopping cart. } }
More
Less