更新:2007 年 11 月
如果您使用的是带模板的数据绑定控件(例如,DataList 或 FormView 控件),且模板包含 Button、LinkButton 或 ImageButton Web 服务器控件,则按钮可以将它们的 Click 事件转发给包含控件。这样,您可以包含按钮以实现尚未为数据绑定控件定义的自定义功能,例如,编辑、删除、更新和取消。
响应数据绑定控件中的按钮事件
在控件模板中添加 Button、LinkButton 或 ImageButton。
将按钮的 CommandName 属性设置为标识其功能的字符串,如“排序”或“复制”。
创建用于控件的 ItemCommand 事件的方法。在该方法中,执行下列操作:
检查事件参数对象的 CommandName 属性来查看传入什么字符串。
为用户单击的按钮执行相应的逻辑。
下面的示例演示响应 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)