Search code examples
c#user-controls

access form from usercontrol


I have a user control, that needs to access variables and static classes on Form1.cs. I can't find a working example on google. Any hints please? Thanks!

namespace WinApp1
{
public partial class Form1 : Form
{
    Public MyCustomClass myClass; // need to access this
    public Form1()
    {

    }
}
public static class Global {
   public static myGlobalVar; // Need to Access This
}
}

Solution

  • Use this.Parent in UserControl to get the parent form :

    Form1 myParent = (Form1)this.Parent;
    

    then you can access the public field/property :

    myParent.myClass 
    

    Note that if the UserControl is placed in a Panel inside the Form, you will need to get parent of parent.

    You can access the static class by its name :

    Global.myGlobalVar