(I'm using default Visual Studio names) How can I reference a texbox object(texbox1) in another custom class in form1.cs file(a class within "public partial class Form1 : Form")
here is my code. In myclass I've written textBox1, but intelisense didn't suggest it to me. I mean. what can I do to make texbox1 show up in intelisence in this situation? changing private to public in form1.Desginer.cs does'nt solve it. plaease answer.
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class myclass
{
textBox1
}
}
In your nested class
myclass
, you do not specify which instance of theForm1
class you are referring to. Add a reference to a particular instance ofForm1
, then you will be able to access itstextBox1
member.Customarily, this can be done like so:
This code uses various patterns that are used in such situations:
owner
is set in the constructor, thereby ensuring that it is nevernull
null
is rejected by the constructorowner
member isreadonly
, so it is safe to say that it will not change during the lifetime of a givenmyclass
instanceWithin a method of
Form1
, you can then create amyclass
instance linked to the currentForm1
instance by invokingnew myclass(this)
.You cant just reference it in your nested class as its part of the
Form1
class, you will have to pass in a referenceExample:
Then in your
Form1
class where you created theMyClass
instance you can pass in yourTextBox
The WinForms designer makes components private by default, and ideally you should not expose components (such as controls) directly because it breaks encapsulation. You should proxy fields that you want to share, like so:
That way you can share data between forms but also maintain encapsulation (though you should choose a more descrptive name than the
TextBox1Value
I chose.