本文介绍了如何将UserControl加载到面板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按button1的面板1中加载usercontrol1,并在按button2的panel1中加载usercontrol2.

我该怎么做?

I want to load usercontrol1 in panel1 on pressing button1 and load usercontrol2 in panel1 on pressing button2.

How can I do that?

推荐答案

// Button1 click event
myPanel1.Controls.Add(userControl1)

// Button 2 click event 

myPanel2.Controls.Add(userControl2)


private void button1_Click(object sender, EventArgs e)
{
    foreach (Control ctrl in panel1.Controls)
    {
        ctrl.Dispose();
    }
    panel1.Controls.Add(new UserControl1());
}
private void button2_Click(object sender, EventArgs e)
{
    foreach (Control ctrl in panel1.Controls)
    {
        ctrl.Dispose();
    }
    panel1.Controls.Add(new UserControl2());
}



或者....

使用如下所示的隐藏和显示方式



Alternatively....

Use hide and show as below

public partial class Form1 : Form
{
    private UserControl1 ctrl1;
    private UserControl2 ctrl2;
    public Form1()
    {
        InitializeComponent();
    }


    private void toggleUserCtrl(object sender, EventArgs e)
    {
        if (sender.Equals(button1))
        {
            ctrl1.Visible = true;
            ctrl2.Visible = false;
        }else if(sender.Equals(button2)){
            ctrl1.Visible = false;
            ctrl2.Visible = true;
        }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        ctrl1 = new UserControl1();
        ctrl2 = new UserControl2();
        panel1.Controls.Add(ctrl1);
        panel1.Controls.Add(ctrl2);
        ctrl1.Visible = true;
        ctrl2.Visible = false;

        button1.Click += new EventHandler(toggleUserCtrl);
        button2.Click += new EventHandler(toggleUserCtrl);

    }
}


这篇关于如何将UserControl加载到面板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:59