I am trying to pass a User user
variable to another form, but for some reason it says that it's value is null
. What did I do wrong?
AuthorizationForm.cs:
public partial class AuthorizationForm : Form
{
public Model.User user;
private void loginButton_Click(object sender, EventArgs e)
{
user = mCollection.Find(u => u.Email == loginBox.Text).FirstOrDefault();
// Logic, which shows, that in this scope user is not null
}
}
MainForm.cs:
public partial class MainForm : Form
{
View.AuthorizationForm authorizationForm = new View.AuthorizationForm();
private void confirmButton_Click(object sender, EventArgs e)
{
// NullReferenceException thrown here because `authorizationForm.user` is null.
MessageBox.Show(authorizationForm.user.Name);
}
}
CodePudding user response:
Try adding constructors to AuthorizationForm
public partial class AuthorizationForm : Form
{
public Model.User user;
public AuthorizationForm()
{
InitializeComponent();
}
private void loginButton_Click(object sender, EventArgs e)
{
user = mCollection.Find(u => u.Email == loginBox.Text).FirstOrDefault();
// Logic, which shows, that in this scope user is not null
}
}
CodePudding user response:
You can pass the input variable to the constructor
when creating an instance of the AuthorizationForm
class.
public partial class AuthorizationForm : Form
{
public Model.User user;
public AuthorizationForm(Model.User _user)
{
user = _user;
}
private void loginButton_Click(object sender, EventArgs e)
{
user = mCollection.Find(u => u.Email == loginBox.Text).FirstOrDefault();
// Logic, which shows, that in this scope user is not null
}
}
Or in the first form the user variable separately
public partial class MainForm : Form
{
View.AuthorizationForm authorizationForm = new View.AuthorizationForm();
authorizationForm.user = yourVaule
//...................................................
}