简体   繁体   中英

How to load user control to a panel by button click in C#

I wanted to load a user control to a panel with a button, but when I tried this code it shows nothing. I wonder if there is a solution for my problem because I've already tried many solutions from internet but nothing worked.

this is my code :

on user cotrol

public partial class UserControl1 : UserControl
{
    public static UserControl1 _instance;
    public static UserControl1 Instance {
        get {
            if (_instance == null)
                _instance = new UserControl1();
            return _instance;
        }
    }
    public UserControl1()
    {
        InitializeComponent();
    }
}

on winform by button click

private void b1_Click(object sender, EventArgs e)
    {
        if (!panel5.Controls.Contains(UserControl1.Instance))
        {
            panel5.Controls.Add(UserControl1.Instance);
            UserControl1.Instance.Dock = DockStyle.Fill;
            UserControl1.Instance.BringToFront();
        }
        else
            UserControl1.Instance.BringToFront();
    }

main form

在此输入图像描述

user control

在此输入图像描述

Thanks for your concern.

try this. Hope this will help .you

private void set2ControlTopanel(control f) {

    try {
        p2Form = f;
        p2Form.Dock = DockStyle.Fill;
        p2Form.Show();
        panelTop.Controls.Add(p2Form);
        p2Form.BringToFront();
    }
    catch (Exception ex) {
        MsgBox(ex.Message);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM