将事件分配给Repeater控件内的自定义控件

我有一个Repeater控件,它的一些单元格中包含一个包含DropDownList的UserControl。 在Repeater控件的ItemDataBound事件中,我将一个事件分配给DropDownList,如下所示:

protected void MyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { ... MyControl myControl = (MyControl)e.Item.FindControl("MyControl01"); myControl.DataSource = myObject; myControl.DataBind(); myControl.DropDownList.SelectedItemChange += MyMethod_SelectedIndexChanged; myControl.DropDownList.AutoPostBack = true; .... } protected void MyMethod_SelectedIndexChanged(object sender, EventArgs e) { //Do something. } 

事件永远不会发生。 我需要帮助。

您的事件未在PostBack中引发,因为您的事件处理程序尚未附加(仅当您的转发器是数据绑定时,它仅在页面生命周期的迭代期间附加)。

如果您在标记中以声明方式附加事件处理程序,例如:

      

然后在PostBacks期间调用您的事件处理程序。

有两件事你可以尝试看看它是否会有所帮助:

  1. 尝试在每个页面请求上绑定MyRepeater,而不仅仅是在什么时候!IsPostBack。
  2. 在OnInit中绑定MyRepeater。

对于1)如果在第一次加载页面时创建动态创建的控件,然后在发生回发时再次创建,ASP.NET将注意到引发的事件匹配并将触发事件。

对于2)设计者总是在OnInit中放置事件附件,尽管它也应该在OnLoad中正常工作。

首先确保您的数据绑定不会重置您的下拉列表。

这是控件的代码,它将嵌套在转发器ItemTemplate中

 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ListBoxContainer.ascx.cs" Inherits="OAAF.Common.ListBoxContainer" %>  

控件的后面代码将嵌套在转发器ItemTemplate中

 public partial class ListBoxContainer : System.Web.UI.UserControl { //declare the event using EventHandler public event EventHandler ListBox_SelectedIndexChanged; protected void Page_Load(object sender, EventArgs e) { } protected void LstFromControl_SelectedIndexChanged(object sender, EventArgs e) { //fire event: the check for null sees if the delegate is subscribed to if (ListBox_SelectedIndexChanged != null) { ListBox_SelectedIndexChanged(sender, e); } } } 

请注意,上面的控件在内部使用列表框更改事件,然后触发自己的事件:ListBox_SelectedIndexChanged。 您也可以在此处创建自定义事件参数,但这会使用标准的EventArgs。

具有控件的转发器可能如下所示

   

例如,在转发器所在的页面顶部注册控件

 <%@ Register Src="~/Common/ListBoxContainer.ascx" TagName="wucListBox" TagPrefix="ctrl" %> 

它处理事件ListBox_SelectedIndexChanged,处理此事件的方法位于转发器所在页面的代码后面。

  protected void ListBoxControl_SelectedIndexChanged(object sender, EventArgs e) { //some code }