C# - 将变量传递给另一个表单
Posted
技术标签:
【中文标题】C# - 将变量传递给另一个表单【英文标题】:C# - passing a variable to another form 【发布时间】:2022-01-15 15:34:06 【问题描述】:我试图将User user
变量传递给另一个表单,但由于某种原因,它说它的值是null
。我做错了什么?
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);
【问题讨论】:
您在MainForm
班级的哪个位置呼叫authorizationForm.Show()
或authorizationForm.ShowDialog()
?
由于您是从MainForm
实例化AuthorizationForm
-- 您可以在该点或稍后在您的程序执行中为其播种。
【参考方案1】:
您可以在创建AuthorizationForm
类的实例时将输入变量传递给constructor
。
public partial class AuthorizationForm : Form
public Model.User user;
public AuthorizationForm(Model.User _user)
InitializeComponent();
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
或者在第一种形式中单独使用用户变量
public partial class MainForm : Form
View.AuthorizationForm authorizationForm = new View.AuthorizationForm();
authorizationForm.user = yourVaule
//...................................................
【讨论】:
不幸的是,WinForms 设计器要求 Form 子类有一个无参数的构造函数(从而嘲弄依赖注入模式)。 别忘了在 ctor 内部调用InitializeComponent()
。【参考方案2】:
尝试向 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();
//------------------------------------
【讨论】:
以上是关于C# - 将变量传递给另一个表单的主要内容,如果未能解决你的问题,请参考以下文章