从一个用户控件调用另一个用户控件

时间:2018-05-15 12:41:37

标签: c#

我有两个用户控件usercontrol_1和usercontrol_2,使用点击事件我将usercontrol_1引入我主表单上名为panel_screen的面板。

private void btn_Click(object sender, EventArgs e)
        {

            if (!panel_screen.Controls.Contains(usercontrol_1.Instance))
            {
                panel_screen.Controls.Add(usercontrol_1.Instance);
                usercontrol_1.Instance.Dock = DockStyle.Fill;
                usercontrol_1.Instance.BringToFront();
            }
            else
                usercontrol_1.Instance.BringToFront();
        }

同样,我想使用usercontrol_1上的按钮(click事件)将usercontrol_2带到主窗体上的同一面板。 我该怎么做呢?任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:0)

我不确定您遇到问题的地方,我认为您使用usercontrol_1.Instance的方式可能会导致问题。

我在这里有工作的例子,你可以试试。

private void btn_Click(object sender, EventArgs e)
{
    bool userControlIsAlreadyInPanel = false;

    //assuming you are cheking if usercontrol_1 is already there on panel
    // you don't want to create new usercontrol, but just bring existing control to the front
    foreach(UserControl control in panel_screen.Controls)
    {
        if (control.GetType() == typeof(usercontrol_1))
        {
            userControlIsAlreadyInPanel = true;
            control.BringToFront();
        }
    }

    if(!userControlIsAlreadyInPanel)
    {
        usercontrol_1 instane = new usercontrol_1();

        panel_screen.Controls.Add(instane);
        instane.Dock = DockStyle.Fill;
        instane.BringToFront();
    }
}

<强>输出

enter image description here

答案 1 :(得分:0)

    namespace WindowsFormsApp1
    {
public partial class usercontrol_2 : UserControl
{
    public event MyEventDelegate userControlButtonClicked;
    public usercontrol_2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MyEventDelegate med = userControlButtonClicked;
        if (med != null)
        {
            med(this, "2");
        }
    }
}
    }

}

UPDATE PR PR1 
LEFT JOIN PR PR2 ON PR2.a = PR1.a AND PR2.b = PR1.b
SET PR1.PR_KEY = 1
WHERE PR2.a IS NULL

}

{{1}}