Get access to parent control from user control - C#

后端 未结 9 1798
甜味超标
甜味超标 2020-11-29 06:42

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.

9条回答
  •  [愿得一人]
    2020-11-29 07:04

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

提交回复
热议问题