Accessing MainForm textbox data in Visual c#
I have a form with a number of text boxes. I want开发者_StackOverflow中文版 to create a class (InputData
) to collect and store this data but I am unable to access the txtBox.Text
. I can see some of the points at which I am being blocked. i.e. private text box declarations in the MainForm class etc. The MainForm.Designer contains the warning:
Required method for Designer support - do not modify
the contents of this method with the code editor.
So it stands that I cannot change access levels of the textboxes here. Another block could be that the Mainform needs to be instantiated by the InitializeComponent()
method in MainForm and so textboxes don't yet exist.
The solution I had in mind involves the InputData
constructor pulling values from textboxes and storing internally.
So basically I need advice on the common pattern used to carry out this as I have been searching but have been unable to find a solution.
Thanks for any solutions offered!
A standard pattern that I follow for WinForm applications is to create a Dialog Data Model (that is what I call it -- I am not suggesting I invented it or anything). This class contains all of the data to be set or retrieved from the form. Each form provides a consistently named SetXXXData and GetXXXData method which populates the model or form:
struct InputData
{
string Text;
}
and then in your form:
void MyForm::SetInputData(InputData data)
{
myControl.Text = data.Text;
}
void MyForm::GetInputData(InputData data)
{
data.Text = myControl.Text;
}
It is not that impressive until you have a form with lots of data in it. It keeps all of the form controls in the form and does not expose your application to the inner workings fo the UI. By abstracting out the data you also have the benefit of changing the control types down the road withtout effecting the callers.
How about exposing the textbox values as properties of the MainForm? That way you can access them from any other class that has access to MainForm. Like this:
public string TextBoxText
{
get
{
return textBox.Text;
}
}
FYI, you can change the access level of an element by changing the "Modifiers" property in the designer. It has options for public, protected, private, etc...
You can make the TextBox public. Just select in the properties window of the textbox under Design/Modifiers and select public.
精彩评论