[c#] Get access to parent control from user control - C#

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.

This question is related to c# winforms user-controls

The answer is


You can get the Parent of a control via

myControl.Parent

See MSDN: Control.Parent


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.


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;


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

}

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!


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

((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


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to user-controls

How do I add my new User Control to the Toolbox or a new Winform? Get access to parent control from user control - C# How do I make an Event in the Usercontrol and have it handled in the Main Form? How to calculate the sum of the datatable column in asp.net? User Control - Custom Properties Add a user control to a wpf window "The Controls collection cannot be modified because the control contains code blocks" Disposing WPF User Controls How do I get the full url of the page I am on in C#