How to get userControl2 from button click on userControl1 into panel2?
Pressing the button New
shows userControl1
control on Panel1
, but I want to show usercontrol2
by pressing userControl1
button to panel2
userControl2
. I couldn't do it.
private void btnNewDay_Click(object sender, EventArgs e) {
frmMain main = new frmMain();
main.panel2.Controls.Clear();
userControls.ucNewDay newDay = new userControls.ucNewDay();
main.panel2.Controls.Add(newDay);
main.userControlcontrol = true;
}
You're creating a new form with new frmMain();
. What you need is to get a handle of the current form. You can do that by simply using the this
keyword, but this is even optional and you don't have to use anything. However, in a user control, this
refers to the control. In this case use the Parent
property.
Change the first line:
frmMain main = new frmMain();
to:
frmMain main = (frmMain)this.Parent;
Alternatively, you can use the FindForm()
method:
frmMain main = (frmMain)this.FindForm();