I have a main form with some buttons, textboxes, labels, etc.
On a second form I would like to copy the text from the main forms textbox onto the second form.
Have tried:
var form = new MainScreen();
TextBox tb= form.Controls["textboxMain"] as TextBox;
textboxSecond.Text = tb.Text;
But it just causes an exception. The main screen textbox is initialised and contains text.
When I hover over form I can see all the controls are there.
What am I doing wrong?
Looking at the original code, there are two potential reasons for the
NullReferenceExceptionyou are getting. First,tbis not defined in the code you provide so I am not sure what that is.Secondly,
TextBox textbox = form.Controls["textboxMain"] as TextBoxcan returnnullif the control is not found or is not aTextBox. Controls, by default, are marked with theprivateaccessor, which leads me to suspect thatform.Controls[...]will returnnullforprivatemembers.While marking the controls as
internalwill 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.privateaccessors on controls are perfectly fine.A better way to share the data between the forms would be with
publicproperties. For example, let’s say you have aTextBoxon your main screen calledusernameTextBoxand want to expose it publicly to other forms:Then all you would have to do in your code is:
The great part about this solution is that you have better control of how data is stored via properties. Your
getandsetactions 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.