Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Proper way to get reference of a control on the form

Tags:

c#

forms

controls

I have a C# class library which uses a form (which is also in the library). Let's say I have an edit box on this form called editContents. In a regular form application, I'm used to being able to aquire the edit box like this:

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

I guess some magic occurs behind the scenes in a regular forms application, because the edit box member is private in the MainForm class, but I can still access it like a public member.

But in my class library I can't access the edit box like this. I instantiate and show the form "manually" like this:

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

How do I properly acquire the editContents control from this form?

like image 286
sharkin Avatar asked Nov 30 '22 06:11

sharkin


2 Answers

You could make it a publicly accessible Property, by adding some code like this:

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; }
}
like image 145
Donut Avatar answered Dec 10 '22 23:12

Donut


The "magic" is that a field is generated for your textbox in the *.Designer.cs file. By default, this field is private. If you want to change it's accessibility, select your text box in the forms designer, and change the "Modifiers" property to Public.

This might however not be a good idea to expose publicly all controls of your form. You can instead wrap it around in a property like Donut suggests, which is cleaner.

like image 35
Julien Lebosquain Avatar answered Dec 10 '22 21:12

Julien Lebosquain