【问题标题】:Issue Related to UserControl in ASP.net与 ASP.net 中的 UserControl 相关的问题
【发布时间】:2013-02-22 09:33:17
【问题描述】:

我有一个 asp.net web 应用程序,我在母版页下有一个 aspx 页面。我有两个 UserControl:(1) UC1 (2) UC2。 UC1添加在母版页面设计中,UC2添加在aspx页面设计中..

现在我在 UC1 上有一些复选框,将 AutoPostback 属性设置为 True。在 Checked_Change 事件中,我在 Session 中添加了一些值。然后我想调用 UC2 userControl 中的函数

但问题是,当复选框选中时,UC2'代码首先执行,然后 UC1 的代码执行.. 所以在 UC2 的代码中没有找到在 UC1 的代码中添加的任何会话值

那么如何改变UserControls的代码执行顺序???

有没有办法通过UC1找到MasterPage的子页面???

谢谢

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    是的,这不是控件之间通信的好方法,使用会话也不是一个好习惯。但是,您可以这样做:

    在母版页上,使用ContentPlaceHolder 尝试查找UC2,您需要其ID 才能使用FindControl 方法:

    Control ctrl = ContentPlaceHolder.FindControl("UC2_ID");
    
    if (ctrl != null && ctrl is UC2)
    {
        UC2 uc2 = (UC2)ctrl;
    
        uc2.TakeThisStuff(stuff);
    }
    

    或者,如果您真的不知道它的 ID,您可以遍历 ContentPlaceHolder 控件,直到找到类型为 UC2 的控件。

    public T FindControl<T>(Control parent) where T : Control
    {
        foreach (Control c in parent.Controls)
        {
            if (c is T)
            {
                return (T)c;
            }
            else if (c.Controls.Count > 0)
            {
                Control child = FindControl<T>(c);
                if (child != null)
                    return (T)child;
            }
        }
    
        return null;
    }
    

    像这样使用它:

    UC2 ctrl = FindControl<UC2>(ContentPlaceHolder);
    
    if (ctrl != null)
    {
        UC2 uc2 = (UC2)ctrl;
    
        uc2.TakeThisStuff(stuff);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多