这是来自ascx的具有中继器的代码:
<asp:Repeater ID="ListOfEmails" runat="server" > <HeaderTemplate><h3>A sub-header:</h3></HeaderTemplate> <ItemTemplate> [Some other stuff is here] <asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" /> </ItemTemplate> </asp:Repeater>
在中继器的数据绑定和事件的代码中:
Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object,ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"),Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click,AddressOf removeEmail_Click AddHandler removeEmail.Command,AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object,ByVal e As System.EventArgs) Response.Write("<h1>click</h1>") End Sub Sub removeEmail_Command(ByVal sender As Object,ByVal e As CommandEventArgs) Response.Write("<h1>command</h1>") End Sub
点击或命令都没有被调用,我做错了什么?
解决方法
嵌套在中继器内部的控件不会拦截事件.相反,您需要绑定到Repeater.ItemCommand事件.
ItemCommand包含RepeaterCommandEventArgs,它有两个重要的字段:
> CommandName
> CommandArgument
所以,一个微不足道的例子:
void rptr_ItemDataBound(object sender,RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // Stuff to databind Button myButton = (Button)e.Item.FindControl("myButton"); myButton.CommandName = "Add"; myButton.CommandArgument = "Some Identifying Argument"; } } void rptr_ItemCommand(object source,RepeaterCommandEventArgs e) { if (e.CommandName == "Add") { // Do your event } }
编辑:Markdown完全希望我的缩进,哦,我应该停止在这个文本框中编写代码.