Looking at the original code, there are two potential reasons for the NullReferenceException
you are getting. First, tb
is not defined in the code you provide so I am not sure what that is.
Secondly, TextBox textbox = form.Controls["textboxMain"] as TextBox
can return null
if the control is not found or is not a TextBox
. Controls, by default, are marked with the private
accessor, which leads me to suspect that form.Controls[...]
will return null
for private
members.
While marking the controls as internal
will potentially fix this issue, it's really not the best way to tackle this situation and will only lead to poor coding habits in the future. private
accessors on controls are perfectly fine.
A better way to share the data between the forms would be with public
properties. For example, let's say you have a TextBox
on your main screen called usernameTextBox
and want to expose it publicly to other forms:
public string Username
{
get { return usernameTextBox.Text; }
set { usernameTextBox.Text = value; }
}
Then all you would have to do in your code is:
var form = new MainForm();
myTextBox.Text = form.Username; // Get the username TextBox value
form.Username = myTextBox.Text; // Set the username TextBox value
The great part about this solution is that you have better control of how data is stored via properties. Your get
and set
actions can contain logic, set multiple values, perform validation, and various other functionality.
If you are using WPF I would recommend looking up the MVVM pattern as it allows you to do similar with object states.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…