如何从asp.net中的子UserControl调用父UserControl方法?

0 c# asp.net user-controls

我必须在子usercontrol中使用父usercontrol方法的结果.如何在子控件中找到方法?

Ewe*_*ton 11

存在用户控件以使我们的代码更可重用,用户控件可以放在任何页面中,某些页面可能有这两个用户控件,有些页面没有,因此您无法确保该页面将具有两个用户控件.在我看来,最好的方法是使用事件.这个想法如下:子usercontrol引发一个事件,放置此用户控件的页面处理此事件并调用父用户控件的事件,这样,您的代码仍然可以重用.

因此,儿童控制的代码如下

public partial class Child : System.Web.UI.UserControl
{
    // here, we declare the event
    public event EventHandler OnChildEventOccurs;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // some code ...
        List<string> results = new List<string>();
        results.Add("Item1");
        results.Add("Item2");

        // this code says: when some one is listening this event, raises this and send one List of string as parameters
        if (OnChildEventOccurs != null)
            OnChildEventOccurs(results, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

并且页面需要处理此事件的发生,如下所示

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // the page will listen for when the event occurs in the child
        Child1.OnChildEventOccurs += new EventHandler(Child1_OnChildEventOccurs);
    }

    void Child1_OnChildEventOccurs(object sender, EventArgs e)
    {
        // Here you will be notified when the method occurs in your child control.
        // once you know that the method occurs you can call the method of the parent and pass the parameters received
        Parent1.DoSomethingWhenChildRaisesYourEvent((List<string>)sender);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后是在父控件中执行某些操作的方法.

 public void DoSomethingWhenChildRaisesYourEvent(List<string> lstParam)
    {
        foreach (string  item in lstParam)
        {
            // Just show the strings on the screen
            lblResult.Text = lblResult.Text + " " + item;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这样,您的页面就充当了事件的协调者.