[英]How to give property a Value from another class
I have 2 classes: FrmMenu
and FrmProperty
. 我有2个类:
FrmMenu
和FrmProperty
。 In FrmProperty
I created a property like this: 在
FrmProperty
我创建了一个像这样的属性:
public string ApplicationString { get; set; }
form1_load(object sender, EventArgs e)
{
MessageBox.Show(ApplicationString);
}
Then, I instantiate that class in FrmMenu
, like this: 然后,我在
FrmMenu
实例化该类,如下所示:
FrmProperty frmp = new FrmProperty();
//Give value
frmp.ApplicationString = "1";
frmp.ShowDialog();
This code should transfer a value from FrmMenu
to FrmProperty
. 此代码应将值从
FrmMenu
传输到FrmProperty
。 Why doesn't this work? 为什么不起作用? The MessageBox is blank.
MessageBox为空白。
So, I've tried this out myself and the first thing to note is that the code you supply does not compile. 因此,我自己进行了尝试,首先要注意的是您提供的代码无法编译。 Your example has:
您的示例有:
form1_load(object sender, EventArgs e)
{
MessageBox.Show(ApplicationString);
}
but this would be better writen as: 但这最好写成:
private void FrmProperty_Load(object sender, EventArgs e)
{
MessageBox.Show(ApplicationString);
}
Perhaps that is self explanatory but I find it always helps to make sure everything is as clear as possible. 也许这是不言而喻的,但我发现它总是有助于确保一切都尽可能清晰。
In terms of your problem, the only thing I can possibly think of that would make your code fail to work using the above is if you had not wired up the FrmProperty_Load
method to the Load event of FrmProperty
. 就您的问题而言,我可能唯一想到的是,如果您没有将
FrmProperty_Load
方法连接到FrmProperty_Load
的Load事件, FrmProperty
使代码无法使用上述方法FrmProperty
。
The FrmProperty_Load
method won't run unless something asks it to, so in the constructor for FrmProperty
add the following: 除非有要求,否则
FrmProperty_Load
方法将不会运行,因此在FrmProperty
的构造函数中添加以下内容:
this.Load += FrmProperty_Load;
Your FrmMenu
class should remain unchanged and your FrmProperty
class should look roughly like the following: 您的
FrmMenu
类应保持不变,而FrmProperty
类应大致如下所示:
public partial class FrmProperty : Form
{
public string ApplicationString { get; set; }
public FrmProperty()
{
InitializeComponent();
this.Load += FrmProperty_Load;
}
private void FrmProperty_Load(object sender, EventArgs e)
{
MessageBox.Show(ApplicationString);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.