This is the case scenario: if you have a form and in the form you have a button, if you press the button can you actually see a User Control displayed?. A friend of mine asked me this question because in his form he was trying to display a user control doing this:
private void button1_Click(object sender, EventArgs e)
{
UserControl1 userControl = new UserControl1();
userControl.Show();
}
This will not do the trick. What you need to do is to create a form, add the user control to the form, and then display the form. This is a simple way of doing this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Show(Control control)
{
Form form = new Form();
form.Controls.Add(control);
form.Show();
}
private void button1_Click(object sender, EventArgs e)
{
UserControl1 userControl = new UserControl1();
Form1 form = new Form1();
form.Show(userControl);
}
}
At this point you will be able to see your user control displayed inside a form.
C#: Show a User Control
One Response
Leave a Comment
November 8th, 2007 at 3:34 am
Your method actually creates a new Form with ‘minimize’,'maximize’,close’ buttons, borders and all that stuff.
Why is it not possible to add Objects directly to a Form?