I need some Help here. I have 4-5 user controls stacked upon one another.All are of same size and only the one on top is visible. I have a button on the top most user control. I wish that when I click the button that usercontrol is sent to back and another user control is brought to front. This is my Code:
private void btnaddcstmrdashbrd_Click(object sender, EventArgs e)
{
addorder addorder = new addorder();
this.Visible = false;
this.SendToBack();
addorder.Visible = true;
addorder.BringToFront();
}
What happens is, The top most userControl is no more visible. However the other user Control does not com to front and is not visible. I would really appreciate some help.
If the user controls are in different types, you can refer to the following code. Bind the same method to the button that in user control, and use switch to judge the user control type.
UserControl1 userControl1 = new UserControl1();
UserControl2 userControl2 = new UserControl2();
UserControl3 userControl3 = new UserControl3();
private void Form1_Load(object sender, EventArgs e)
{
Button button1 = new Button
{
Text = "Next Control",
Dock = DockStyle.Bottom,
};
button1.Click += Button_Click;
Button button2 = new Button
{
Text = "Next Control",
Dock = DockStyle.Bottom,
};
button2.Click += Button_Click;
Button button3 = new Button
{
Text = "Next Control",
Dock = DockStyle.Bottom,
};
button3.Click += Button_Click;
userControl1.Controls.Add(button1);
userControl2.Controls.Add(button2);
userControl3.Controls.Add(button3);
Controls.Add(userControl1);
Controls.Add(userControl2);
Controls.Add(userControl3);
}
private void Button_Click(object sender, EventArgs e)
{
string controlName = ((Button)sender).Parent.Name;
switch (controlName)
{
case "UserControl1":
userControl2.BringToFront();
break;
case "UserControl2":
userControl3.BringToFront();
break;
case "UserControl3":
userControl1.BringToFront();
break;
}
}
The test result,
Update
If the button is added from designer, you can refer to the following code.
First, define the usercontrol property in Form1.cs. And pass the Form object via parameter.
public partial class Form1 : Form
{
public static Form1 form1;
public Form1()
{
InitializeComponent();
form1 = this;
}
public UserControl1 UC1{get;set;}
public UserControl2 UC2{get;set;}
public UserControl3 UC3{get;set;}
private void Form1_Load(object sender, EventArgs e)
{
UC1 = new UserControl1(form1);
UC2 = new UserControl2(form1);
UC3 = new UserControl3(form1);
Controls.Add(UC1);
Controls.Add(UC2);
Controls.Add(UC3);
}
}
Then, modity the code in UserControl1.cs.
public partial class UserControl1 : UserControl
{
public Form1 f1;
public UserControl1(Form1 form1)
{
InitializeComponent();
f1 = form1;
}
// this button is dragged and dropped from toolbox
private void button1_Click(object sender, EventArgs e)
{
f1.UC2.BringToFront();
//f1.UC3.BringToFront();
//f1.UC1.BringToFront();
}
}
Do the same for the rest of UserControls.