概述:

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

这是一个WinForm应用程序,具有两种形式,分别名为form1PostCodeForm。我需要将数据从短暂的表单PostcodeForm通过clickEvent传递回Form1,然后关闭该表单。这些值存储在dataTable类的PostcodeSearch中,并通过以下方式访问它们:


遍历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;

Form1中创建PostCodeForm的实例:

Form1 formIndi = new Form1();

然后创建一些局部变量,这些局部变量在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;

然后将它们传递给Form1(在PostCodeForm中):

formIndi.txt_City.Text = _StreetName_Cell.ToString();
formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
formIndi.txt_ District.Text = _District_Cell.ToString();



我需要将数据传递回主窗体并将其存储在相关的textBoxes中。

问题

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

最佳答案

正如@ 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();

关于c# - 将数据从一种形式传递到另一种形式的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44411751/

10-10 13:01