Reputation: 1388
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
}
}
Upvotes: 3
Views: 19582
Reputation: 138
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);
Upvotes: 0
Reputation: 11
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 :-)
Upvotes: 1
Reputation: 1462
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.
Upvotes: 3
Reputation: 5433
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
Upvotes: 8
Reputation: 12557
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..
Upvotes: 5
Reputation: 226
I thought that this.Parent returns the actual page that the user control is placed? And then you access the public members
Upvotes: 1