可以使用事件参数的 CommandName 属性在事件处理程序方法中标识按钮的功能。如果使用的是 ButtonField 或 TemplateField 对象,则还可以使用 CommandArgument 属性来标识当前行。使用的是 ButtonField 对象时,CommandArgument 属性自动设置为行索引。使用的是 TemplateField 对象时,控件不会自动设置 CommandArgument 属性。在这种情况下,如果必须在事件处理程序中确定行索引,则可以使用数据绑定表达式将该按钮的 CommandArgument 属性设置为行索引。
-
将按钮的 CommandName 属性设置为标识其功能的字符串,如“打印”或“复制”。
-
如果使用的是 TemplateField 对象并且必须在事件处理程序方法中访问行索引,则将按钮的 CommandArgument 属性设置为标识当前行的表达式。
下面的示例演示如何将 TemplateField 列中某个按钮的 CommandArgument 属性设置为当前行索引。在该示例中,该列包含一个显示购物车的 Button 控件。
-
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField> -
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.
}