Get access to parent control from user control - C#

后端 未结 9 1800
甜味超标
甜味超标 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:06

    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.

    0 讨论(0)
  • 2020-11-29 07:07

    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!

    0 讨论(0)
  • 2020-11-29 07:10
    ((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

    0 讨论(0)
提交回复
热议问题