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

c#, controls, forms

Solution

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; }
}

Problem

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?

Original source