Access form panel from user control?
In my project, I used a Windows Form and user controls. There is a panel on the form. And I put user controls on it.
When I click a button on the user control, I want to load another user control on the Windows Form panel. I set the panel's modifiers public.
The code I tried is below, this are the used variables:
myusercontrolpage1
: this is my first user controlmyusercontrolpage1
: this is my second user controlFrmMain
: this is my main formpnlOrta
: this is my panel I load user control in it
This is the code, which is not working:
Userclasses.myusercontrolpage1 page1 = new Userclasses.myusercontrolpage1();
Userclasses.myusercontrolpage2 page2 = new Userclasses.m开发者_如何学运维yusercontrolpage2();
FrmMain pnl = new FrmMain();
pnl.pnlOrta.Controls.Clear();
pnl.pnlOrta.Controls.Add(page2);
pnl.pnlOrta.Dock = DockStyle.Fill;
pnl.pnlOrta.BringToFront();
When I click a button on the user control, I want to load another user control on a Windows Form panel.
How can I access form's panel from user control and load another user control?
EDIT:
I replaced this:
FrmMain pnl = new FrmMain();
to
FrmMain f = (FrmMain)this.ParentForm;
This worked.
I'm not sure if I understand what you're trying to do, but answering this part of your question:
How can i access form's panel from usercontrol...
If you know your UserControl is going to be load on Panel, then you can use .Parent property. You can do something like this in your UserControl (suppose it has a button):
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Panel pnl = this.Parent as Panel;
if (pnl != null)
{
pnl.BackColor = Color.Red;
}
}
}
精彩评论