Hi everyone,
I want to create a form that can change user control dynamically at runtime, for example when I press button 1 from form A, form B will load with user control 1, but when button 2 is pressed (from form A of course), user control 2 will be loaded in form B. Do you have any idea how I could start it?
Thanks for reading!
Loading
Ashley ArgilePosted Oct 2, 2008, 5:15 PM
To add a user control to a form at runtime you simply add an instance to the forms Controls collection. e.g.
UserControl1 userControl = new UserControl1();
this.Controls.Add(userControl);
you can specify the position of the control on the target form using
userControl.Location = new Point(10,10);
You could place a panel on the target form at design time and then add the user control dynamically to that. If you ensure that the user control is the same size as the panel then you won't have to worry about positioning.
You could also have the user control conform to an interface and then have the constructor of the target form take an object of that interface as a parameter. This would allow you to host any conforming control in the form. e.g.
public FormB(IControlInterface control)
{
if (control != null)
this.Controls.Add(control);
control.Location = new Point(10, 10);
InitializeComponent();
}
You'd invoke it from Form A as follows (in this case from a button click event handler)
private void button1_Click(object sender, EventArgs e)
{
FormB formB = new FormB(new UserControl1());
formB.ShowDialog();
}
Hope this helps and if you need more examples or a sample then give me a shout.
Regards
Ash.