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?
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; }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With