GridViews allow commands to be sent from a GridView row. This is useful for passing row-specific information into an event handler as command arguments.
To subscribe to a command event:
<asp:GridView ID="GridView1" ... OnRowCommand="GridView1_RowCommand">
Buttons are the most common way to raise commands. They also support a way to specify command arguments. In this example, the argument is an ID
of the item that the row represents.
<TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="SampleCmd"
CommandArgument='<%# Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</TemplateField>
Alternatively, one can use a CommandField
column template that provides the most common command controls.
Handling of the event in code behind:
protected void GridView1_RowCommand(object source, GridViewCommandEventArgs e)
{
if (e.CommandName == "SampleCmd")
{
var id = e.CommandArgument;
}
}
Note that the CommandName
used in this example is arbitrary and is a choice of the developer. There is, however, a set of predefined names that the GridView itself recognizes. Corresponding events are raised when these commands are fired.
Command Name | Events Raised |
---|---|
Cancel | RowCancelingEdit |
Delete | RowDeleting, RowDeleted |
Edit | RowEditing |
Page | PageIndexChanging, PageIndexChanged |
Select | SelectedIndexChanging, SelectedIndexChanged |
Sort | Sorting, Sorted |
Update | RowUpdating, RowUpdated |