Access form from usercontrol

I have a user control that needs to access variables and static classes in Form1.cs. I can not find a working example in google. Any clues 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 } } 
+2
source share
6 answers

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

 Form1 myParent = (Form1)this.Parent; 

then you can open the public field / property:

 myParent.myClass 

Please note that if UserControl is placed in a panel inside the form, you will need to get the parent element of the parent.

You can access the static class by its name:

 Global.myGlobalVar 
+6
source

You can use FindForm ()

But you have to take a step back and see if this is the best solution. This is a strong addiction that reduces the check and reuse ratio of your control.

For example, consider introducing an interface with the elements that you need for your control, and search the parent hirachi or enter it as a parameter, ...

From there you can use the control in my situations. There may be many more solutions. I just want to make you think if there is nothing better than relying on form.

+4
source

Using:

 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 basic form. any change to frm will be reflected in the main form. if you want to access the specified control in your main form, use:

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

 Label lbl_main; 

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

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

3-Make your changes to the shortcut:

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

Your changes will be reflected in the control. Hope this helps.

+2
source

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

+1
source

in your UserControl code, in the Click Event section or something else:

 private void sendParamToMainForm_Button_Click(object sender, EventArgs e) { mainForm wForm; wForm = (mainForm)this.FindForm(); wForm.lblRetrieveText.text = "whatever ..."; } 

Hope this helps :-)

0
source

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

  Main_Form myform = (Main_Form)ParentForm; MessageBox.Show(myform.Label2.Text); 
0
source

Source: https://habr.com/ru/post/1210611/


All Articles