Reputation: 637
I just want to open a Usercontrol (which contains buttons and textboxes) in a windows form when I click a button.
I created form1 with button1 and botton2 and also created Usercontrol1 and Usercontrol2 . now in form1 I want to call Usercontrol1 (open it in form1) when button1 is pressed and then press button2 to show Usercontrol2 and hide Usercontrol1 but I dont know how to do it. I created an object for Usercontrol1 in form1 (Usercontrol1.visible = true/False) but it didnt work. please help. Thank you
here is the code:
public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Usercontrol1 uc1 = new Usercontrol1 ();
uc1.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
Usercontrol1 uc1 = new Usercontrol1 ();
uc1.Visible = false;
Usercontrol2 uc2 = new Usercontrol2 ();
uc2.Visible = true;
}
}
Upvotes: 0
Views: 7258
Reputation: 6671
It should be like this
private void button_Click(object sender, EventArgs e)
{
if(this.Controls.Contains(this.userControl1))
this.Controls.Remove(this.userControl1);
if(!this.Controls.Contains(this.userControl2))
this.Control.Add(this.userControl2);
}
private void button2_Click(object sender, EventArgs e)
{
if(!this.Controls.Contains(this.userControl1))
this.Control.Add(this.userControl1);
if(this.Controls.Contains(this.userControl2))
this.Controls.Remove(this.userControl2);
}
Upvotes: 1