【问题标题】:Subscribing to a single usercontrol event in multiple pages,asp.net 4.0多页面订阅单个usercontrol事件,asp.net 4.0
【发布时间】:2012-08-24 18:54:22
【问题描述】:

我有一个带有 asp.net 服务器端按钮控件的用户控件。我在多个页面上使用此用户控件。我在用户控件的按钮单击事件上引发自定义事件。使用此用户控件的所有父页面都应收到我从用户控件引发的此自定义事件的通知。除了在所有父页面中订阅此事件之外,是否有一种简单的方法可以让我在父页面中获得有关此自定义事件的通知?

我尝试在一个抽象基类中订阅此用户控件事件,该基类覆盖父页面的OnLoad() 事件,并让所有父页面都继承自此抽象基类。后面的usercontrol代码是:

public partial class CustomPaging : System.Web.UI.UserControl
    {
         public delegate void NavigationButtonHandler(int currentPage);

         public event NavigationButtonHandler NavigationButtonClicked;
         public int CurrentPage { get; set; }

         protected void btnPrev_ServerClick(object sender, EventArgs e)
        {
            if (NavigationButtonClicked != null)
            {


                    NavigationButtonClicked(CurrentPage);


            }
        }

  }

而抽象基类是:

public abstract  class CustomPagingBase 
    {

        protected override void OnLoad(EventArgs e)
        {

                 base.OnLoad(e);
                ((CustomPaging)this.FindControl("ucPaging")).NavigationButtonClicked += new CustomPaging.NavigationButtonHandler(CustomPagingBase_NavigationButtonClicked);
        }

        void CustomPagingBase_NavigationButtonClicked(int currentPage)
        {
            LoadData(currentPage);
        }

        protected abstract void LoadData(int currentPage);


    }

但是 this.FindControl("ucPaging") 的部分返回 null。请注意,我有一个 id 为 ucPaging 的用户控件,我在父页面的标记中以声明方式设置

【问题讨论】:

    标签: asp.net user-controls


    【解决方案1】:

    FindControl 默认不递归搜索。

    因此,除非您的 ucPaging 控件直接添加到实现您的抽象类的控件集合中,否则您将得到一个 null。

    你可以使用这个功能找到它

        public static Control FindControlRecursive(this Control control, string id)
        {
            if (control == null) return null;
            //try to find the control at the current level
            Control ctrl = control.FindControl(id);
            if (ctrl == null)
            {
                //search the children
                foreach (Control child in control.Controls)
                {
                    ctrl = FindControlRecursive(child, id);
                    if (ctrl != null) break;
                }
            }
            return ctrl;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多