问题将数据从一个表单传递到另一个表单

时间:2017-06-07 11:45:54

标签: c# .net winforms

概述

将数据从一种形式传递到另一种形式。

这是一个WinForm应用程序,它有两个表单,名为form1PostCodeForm。我需要将数据从短期格式PostcodeForm传递回Form1到clickEvent,然后关闭表单。这些值存储在dataTable类的PostcodeSearch中,并且可以访问它们:

  1. PostCodeForm

    中循环访问dataTable
    for (var item = 0; item < retreiveResults.Count; item++)
    {
        var num = dataGridView2.Rows.Add();
        dataGridView2.Rows[num].Cells[0].Value = retreiveResults[item].City;
        dataGridView2.Rows[num].Cells[1].Value = retreiveResults[item].District;
        dataGridView2.Rows[num].Cells[2].Value = retreiveResults[item].HouseName;
    
  2. Form1中创建了PostCodeForm的实例:

    Form1 formIndi = new Form1();
    
  3. 然后创建了一些局部变量,这些变量在PostCodeForm

    循环结束之前初始化
    var _City_Cell = dataGridView2.Rows[num].Cells[0].Value;
    var _District_Cell = dataGridView2.Rows[num].Cells[1].Value;
    var _HouseName_Cell = dataGridView2.Rows[num].Cells[2].Value;
    
  4. 然后将它们传递给Form1(在PostCodeForm中):

    formIndi.txt_City.Text = _StreetName_Cell.ToString();
    formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
    formIndi.txt_ District.Text = _District_Cell.ToString();
    
  5. 我需要将数据传回主表单并将其存储在相关的文本框中。

    问题

    我的问题是我的textBoxes都没有用给定的值更新,但是当我调试postCodeForm中的Vars时,我可以看到值,所以我不知道为什么TextBoxes没有显示值,因为我一直从表单传递数据以这种方式形成。

2 个答案:

答案 0 :(得分:3)

由于@ Ferus7指出您正在创建Form1的新实例,而不是更新主表单中的值。

//new instance with new text boxes and values
Form1 formIndi = new Form1();
//updates the control in the new form, doesn't affect the caller.
formIndi.txt_City.Text = _StreetName_Cell.ToString();

如果您想从PostcodeForm检索值,可以通过多种方式进行检索。一种选择是在PostcodeForm中声明属性/方法并通过它们检索值:

//declaration in PostcodeForm
class PostcodeForm {
//...
public string StreetName {get; private set;}

//after data retrieval
StreetName = _StreetName_Cell.ToString();


//call PostcodeForm from Form1
postcodeForm = new PostcodeForm();
postcodeForm.ShowDialog();
//after that, get the value
txt_City.Text = postcodeForm.StreetName;

另一种方法是将Form1的引用传递给PostcodeForm

class PostcodeForm {
//declare field
private final Form1 parent;
//create a constructor that accepts `Form1`
PostcodeForm(Form1 parent) 
{
    this.parent = parent;
    //... (InitializeComponents, etc.)
}

//update parent as necessary
parent.txt_City.Text = postcodeForm.StreetName;


//Sample call from Form1
postcodeForm = new PostcodeForm(this);
postcodeForm.ShowDialog();    

答案 1 :(得分:1)

渲染新实例表单

Form1 PostCodeForm= new Form1();
PostCodeForm.Show();
Application.Run();