34

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.

CAbbott
  • 8,078
  • 4
  • 31
  • 38
Farid-ur-Rahman
  • 1,809
  • 9
  • 31
  • 47

9 Answers9

65

Description

You can get the parent control using Control.Parent.

Sample

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);

More Information

Update after a comment by Farid-ur-Rahman (He was asking the question)

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

Sample

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.

  • put a property public MyForm ParentForm { get; set; } to your UserControl
  • set the property in your Form
  • assuming your ListBox is named listBox1 otherwise change the name

Sample

MyForm

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");

    }
}
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • - can you give me a code sample to add item in listbox on form? – Farid-ur-Rahman Jan 11 '12 at 14:48
  • I need more information to help. Is your control placed on a form and on this form is a listbox? So do you want to add to a listbox on a parent control ? – dknaack Jan 11 '12 at 15:04
  • 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. – Farid-ur-Rahman Jan 11 '12 at 15:31
  • Thanks. It works with some changes, I am adding to your answer – Farid-ur-Rahman Jan 12 '12 at 11:18
  • @dknaack I want to get the selected value of ComboBox which is inside the GroupBox from Parent Form. So if I write in this way, `ComboBox cmbOutletGroup = (ParentForm.Controls["cmbOutletGroup"] as ComboBox);`, the result will be null value. How can I access the control inside the container? – Aung Kaung Hein Feb 07 '14 at 07:50
  • Thanks for your answer. It helped me a lot. I achieved it by writing in this way. ComboBox cmbOutletGroup = (ParentForm.Controls["GroupBox1"].Controls["ComboBox1"] as ComboBox); – Aung Kaung Hein Feb 07 '14 at 07:53
  • 1
    `UserControl` have already such property, with that very same name: https://msdn.microsoft.com/en-us/library/system.windows.forms.containercontrol.parentform%28v=vs.110%29.aspx I just noticied when I've had declared a new one in my own class so visual studio give a warning – Jack May 22 '16 at 18:24
11

You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form the control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:

The control's Parent property value might not be the same as the Form returned by FindForm method. For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control's Parent is the GroupBox and the GroupBox control's Parent is the Form.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • Not winforms-specific, but to address the concern that a control's parent might not be the actual form itself i.e. a control within a user control on a form, or even more deeply nested, somethng like this could help depending on performance concerns. EditFormCS is the main page(form): private void SetParentEditForm() { var c = this.Parent; while (c != null && !(c is EditFormCS)) { c = c.Parent; } ParentEditFormCs = c as EditFormCS; } – Allen Oct 21 '20 at 10:46
3

Control has a property called Parent, which will give the parent control. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

eg Control p = this.Parent;

Sprintstar
  • 7,938
  • 5
  • 38
  • 51
2

A generic way to get a parent of a control that I have used is:

public static T GetParentOfType<T>(this Control control)
{
    const int loopLimit = 100; // could have outside method
    var current = control;
    var i = 0;

    do
    {
        current = current.Parent;

        if (current == null) throw new Exception("Could not find parent of specified type");
        if (i++ > loopLimit) throw new Exception("Exceeded loop limit");

    } while (current.GetType() != typeof(T));

    return (T)Convert.ChangeType(current, typeof(T));
}

It needs a bit of work (e.g. returning null if not found or error) ... but hopefully could help someone.

Usage:

var parent = currentControl.GetParentOfType<TypeWanted>();

Enjoy!

Ruskin
  • 5,721
  • 4
  • 45
  • 62
2

According to Ruskins answer and the comments here I came up with the following (recursive) solution:

public static T GetParentOfType<T>(this Control control) where T : class
{
    if (control?.Parent == null)
        return null;

    if (control.Parent is T parent)
        return parent;

    return GetParentOfType<T>(control.Parent);
}
Christian Junk
  • 1,000
  • 1
  • 8
  • 22
2

You can get the Parent of a control via

myControl.Parent

See MSDN: Control.Parent

chaosr
  • 494
  • 2
  • 6
  • 17
1

Not Ideal, but try this...

Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)

Change the usercontrol back to usercontrol class...

Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.

Tery Aldon
  • 11
  • 1
0
((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Asaf
  • 11
  • 1
0

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}
daniele3004
  • 13,072
  • 12
  • 67
  • 75