Ars
Ars

Reputation: 193

Get Usercontrols from controls folder

Need to load usercontrols to my form dynamically. I have menu and passing name of usercontrols when choosing menu items.

private void MenuItemClickHandler(object sender, EventArgs e)
        {
            ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
            MessageBox.Show(clickedItem.Name);
        }

How can load user control in this event? In Asp.Net for such cases i've used LoadControl("path/name.ascx"). I didn't find analog in winforms.

Upvotes: 1

Views: 1110

Answers (3)

Karthik
Karthik

Reputation: 187

You can add the instance either to the current form using Controls.Add() method of the form or the panel that you use in your application.

    public partial class UseUserControl : Form
    {
        public UseUserControl()
        {
            InitializeComponent();
            //Create the user control.
            TempUserControl userControl = new TempUserControl();
            //Add the location to the control.
            userControl.Location = new Point( 40, 40 );
            //Add the control to the current form.
            this.Controls.Add( userControl );
        }
    }

Upvotes: 0

rsbarro
rsbarro

Reputation: 27359

If you have the name of the control, and the controls are already compiled into your application, you can use Activator.CreateInstance to create an instance of the control from the type name. Once you create an instance of the control, you can add it to your form. Something like the code below should work:

private void MenuItemClickHandler(object sender, EventArgs e)
{
    ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
    var t = Type.GetType("MyNamespace." + clickedItem.Name));
    var control = (UserControl)Activator.CreateInstance(t);
    this.Controls.Add(control);    
}

Upvotes: 2

Manas
Manas

Reputation: 2542

This should be simple.

this.Controls.Add(clickedItem)

But before this, you need to set location of clickedItem (i.e. where in form it will be displayed)

Upvotes: 0

Related Questions