How do I get access to the parent controls of user control in C# (winform). I am using the following code but it is not applicable on all types controls such as ListBox.
Control[] Co = this.TopLevelControl.Controls.Find("label7", true);
Co[0].Text = "HelloText"
Actually, I have to add items in Listbox placed on parent 'Form' from a user control.
You can get the parent control using Control.Parent
.
So if you have a Control placed on a form this.Parent
would be your Form.
Within your Control you can do
Form parentForm = (this.Parent as Form);
My Control and a listbox (listBox1) both are place on a Form (Form1). I have to add item in a listBox1 when user press a button placed in my Control.
You have two possible ways to get this done.
1. Use `Control.Parent
MyUserControl
private void button1_Click(object sender, EventArgs e)
{
if (this.Parent == null || this.Parent.GetType() != typeof(MyForm))
return;
ListBox listBox = (this.Parent as MyForm).Controls["listBox1"] as ListBox;
listBox.Items.Add("Test");
}
or
2.
public MyForm ParentForm { get; set; }
to your UserControl
ListBox
is named listBox1
otherwise change the nameMyForm
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
this.myUserControl1.ParentForm = this;
}
}
MyUserControl
public partial class MyUserControl : UserControl
{
public MyForm ParentForm { get; set; }
public MyUserControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ParentForm == null)
return;
ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox);
listBox.Items.Add("Test");
}
}