有很多方法可以将值传递给另一个表单,一种是在被调用表单的constructor 中传递,然后将其传递给local/private property。
假设你在Form1,你打电话给Form2:
Form2 frmCalled = new Form2("Pass this value");
你的Form2 中的constructor 现在将拥有这个
public Form2(String val)
{
InitializeComponent();
this.passval = val;
}
这意味着你有一个名为passval 的property 喜欢:
private string passval { get; set; }
所以,如果你想使用它,那么你现在可以通过简单地调用属性来使用它。例如,如果单击Form2 中的按钮并且您现在想分配该值,那么您将拥有:
private void button1_Click(object sender, EventArgs e)
{
String receivedValue;
receivedValue = passval;
}
另一种方法是使用父窗体中的static 和public 属性,然后从辅助窗体或被调用窗体中调用它。假设在您的 Form1 或 Parent 表单中,您将声明如下:
public static string fromParentForm { get; set; }
假设您正在调用Form2 或被调用的表单,您将这样做:
Form2 frmCalled = new Form2();
fromParentForm = "Parent Form Value here"; // Put value first in your static property
frmCalled.Show();
然后在Form2 中可以访问Parent Form 的值或属性,例如:
private void button1_Click(object sender, EventArgs e)
{
// Value from Parent form static property could be access anywhere in the form
MessageBox.Show(Form1.fromParentForm);
}