如何:响应数据绑定控件中的按钮事件

更新:2007 年 11 月

如果您使用的是带模板的数据绑定控件(例如,DataListFormView 控件),且模板包含 ButtonLinkButtonImageButton Web 服务器控件,则按钮可以将它们的 Click 事件转发给包含控件。这样,您可以包含按钮以实现尚未为数据绑定控件定义的自定义功能,例如,编辑、删除、更新和取消。

响应数据绑定控件中的按钮事件

  1. 在控件模板中添加 ButtonLinkButtonImageButton

  2. 将按钮的 CommandName 属性设置为标识其功能的字符串,如“排序”或“复制”。

  3. 创建用于控件的 ItemCommand 事件的方法。在该方法中,执行下列操作:

    1. 检查事件参数对象的 CommandName 属性来查看传入什么字符串。

    2. 为用户单击的按钮执行相应的逻辑。

    下面的示例演示响应 DataList 控件中的按钮单击的方法。在该示例中,ItemTemplate 包含显示购物车的 ImageButton 控件。该按钮发送命令 AddToCart。事件处理程序确定所单击的是哪个按钮,如果是购物车按钮,则执行相应的逻辑。

    Private Sub DataList1_ItemCommand(ByVal source As Object, _
            ByVal e As DataListCommandEventArgs) _
            Handles DataList1.ItemCommand
        If (e.CommandName = "AddToCart") Then
           ' Add code here to add the item to the shopping cart.
           ' Use the value of e.Item.ItemIndex to find the data row
           ' in the data source.
        End If
    End Sub
    
    private void DataList1_ItemCommand(object source, 
        DataListCommandEventArgs e)
    {
        if (e.CommandName == "AddToCart")
        {
            // Add code here to add the item to the shopping cart.
            // Use the value of e.Item.ItemIndex to find the data row
            // in the data source.
        }
    }
    

请参见

任务

如何:在 ASP.NET 网页中创建事件处理程序 (Visual Studio)

概念

ASP.NET 数据绑定 Web 服务器控件概述