0

我有 2 个表格 1.我通过单击按钮打开然后添加一些form1信息form2form2

    private void button1_Click(object sender, EventArgs e)
    {
        string Name = TxtNewName.Text;
        string City = TxtNewCity.Text
    }

我正在由构造函数打开表单

   private void openForm2_Click(object sender, EventArgs e)
    {
        Form2 newform = new Form2();
        newform.Show();
    } 

当我关闭它时,我想将这个Namecity变量转移到以前打开的表单中,这两个值在已经打开的表单中更新,在 form1 中具有相同名称的字段请帮助我..

4

3 回答 3

2

在第二种形式中定义 2 个公共属性

    public string GetName { get {return TxtNewName.Text;} }
    public string GetCity { get {return TxtNewCity.Text;} }

调用第二个表单后,您可以访问它们

     Form2 form2 = new Form2();
     form2.ShowDialog();

     string name = form2.GetName;
     string city = form2.GetCity;

编辑: ...如果我想在关闭 form2 后直接在 form1 中设置带有名称和城市的文本框的文本属性

this.Text = form2.GetName;
this.city = form2.GetCity;
于 2012-12-28T11:57:51.043 回答
1

您应该公开包含 form2 中的值的属性

public string Name { get { return TxtNewName.Text; } }
public string City { get { return TxtNewCity.Text; } }

并且在

private void openForm2_Click(object sender, EventArgs e) 
{ 
   Form2 newform = new Form2(); 
   newform.ShowDialog(); 
   var city = newform.City;
   var name = newform.Name;
}
于 2012-12-28T11:57:57.827 回答
0

由于您需要将值传递给第一个表单,我会推荐一个参数构造函数来获取您的第一个表单。

设置所需的属性以捕获您需要传递的值Form1

Form2 newform = new Form2(this); // passing instance of Form1
newform.Show();

所以现在您可以访问Form1并分配所需的值。

于 2012-12-28T12:01:00.370 回答