.NET - The correct way to get a link to a control in a form

I have a C # class library that uses a form (which is also in the library). Say I have an edit box in this form called editContents. In the usual form, I'm used to having an edit box as follows:

class MainForm { void Method() { this.editContents.Text = "Hi"; } } 

I guess some kind of magic happens behind the scenes in an application with regular forms, because the edit box element is private in the MainForm class, but I can still access it as an open member.

But in my class library, I cannot access an editing window like this. I create an instance and show the form "manually" as follows:

 form = new MyForm(); form.Show(); 

How can I get the editContents control from this form correctly ?

+4
source share
7 answers

You can make this property public by adding the following code:

 public String EditContents // for just the "Text" field { get { return this.editContents.Text; } set { this.editContents.Text = value; } } 

Or:

 public TextBox EditContents // if you want to access all of the TextBox { get { return this.editContents; } set { this.editContents = value; } } 
+14
source

The magic is that a field is created for your text field in a * .Designer.cs file. By default, this field is private. If you want to change its availability, select your text field in the form designer and change the "Modifiers" property to "Publish".

However, it may not be practical to publicly publish all the controls on your form. You can instead wrap it around, as Donut suggests, which is cleaner.

+5
source

Private members are available in their declaring class. This is why you can access editContents from MainForm.
Private members are not accessible outside their declaring class.
(this is private definition, no magic)

You can wrap it in an open property:

 public TextBox EditContents { get { return this.editContents; } } 
+2
source

In the first case, you can access editContents because you are within the form.

As @Donut said, you can open a property for users of your library to play with it. If you want to restrict access, you can write a method.

eg.

 void SetContentForEditor(string text) { editContent.Text = text; } 

And then you can call SetContentForEditor
eg.

 myForm.SetContentForEditor("hello world"); 
+1
source

You can get it through the Controls collection.

 form.Controls.Find("nameOfControl", true); 
0
source

The difference in accessing the form element inside the Method() vs function using the form link in your last snippet is that your Method() function is a member of your form class and therefore has access to other private members of the class.

0
source

I would introduce an event in the library that notifies all subscribers of this event when a change occurs with the text and must be set in the form. The form should be attached to this event and set the contents of the text field itself.

0
source

All Articles