本文介绍了ASP.Net:为什么我的按钮的单击/命令事件没有在中继器中绑定/触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是来自具有转发器的 ascx 的代码:
Here's the code from the ascx that has the repeater:
<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>
在转发器的数据绑定和事件的代码隐藏中:
And in the codebehind for the repeater's databound and events:
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
点击或命令都没有被调用,我做错了什么?
Neither the click or command is getting called, what am I doing wrong?
推荐答案
嵌套在中继器内部的控件不拦截事件.相反,您需要绑定到 Repeater.ItemCommand
事件.
Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand
Event.
ItemCommand
包含 RepeaterCommandEventArgs
有两个重要的字段:
ItemCommand
contains RepeaterCommandEventArgs
which has two important fields:
- 命令名称
- 命令参数
举个简单的例子:
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
}
}
这篇关于ASP.Net:为什么我的按钮的单击/命令事件没有在中继器中绑定/触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!