3

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
}
}
Kristian
  • 1,348
  • 4
  • 16
  • 39

6 Answers6

8

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 
Abdusalam Ben Haj
  • 5,343
  • 5
  • 31
  • 45
5

You can use FindForm()

But you should make a step back and see if this is the best solution. This is a strong dependency which reduces testability and reuse factor of your control.

For example consider introducing a interface with the members you need for your control and search it in the parent hirachy or Inject it as a parameter ,...

From there on you can use the control on my situations. There may be also many more solutions. Just want to make you think if there isn't anything better than relying on the form..

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
3

Use :

frm_main frm;     //frm_main is your main form which user control is on it
frm=(frm_main)this.FindForm();     //It finds the parent form and sets it to the frm

now you have your main form. any change on frm will be reflected on the main form. if you want to access a specified control on your main form use:

1-Create a control of the type you want to access(Ex:Label):

Label lbl_main;

2-Set the label with returned control from search result:

frm.Controls.FindControl("controlId",true);

3-Make your changes on the Label:

lbl_main.Text="new value changed by user control";

Your changes will be reflected on the control. Hope that helps.

Ali.Rashidi
  • 1,284
  • 4
  • 22
  • 51
1

I thought that this.Parent returns the actual page that the user control is placed? And then you access the public members

d1mitar
  • 226
  • 2
  • 13
1

in your UserControl code, under Click event or whatever:

private void sendParamToMainForm_Button_Click(object sender, EventArgs e)
{
    mainForm wForm;
    wForm = (mainForm)this.FindForm();

    wForm.lblRetrieveText.text = "whatever ...";
}

Hope this helps :-)

0

In case your user control is inside panels and you want to access the form
you can use

        Main_Form myform = (Main_Form)ParentForm;
        MessageBox.Show(myform.Label2.Text);
Ashraf Eldawody
  • 138
  • 3
  • 11