gpt4 book ai didi

c# - 将数据从一种形式传递到另一种形式的问题

转载 作者:行者123 更新时间:2023-11-30 20:30:42 27 4
gpt4 key购买 nike

概览:

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

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

  1. 遍历 PostCodeForm 中的数据表

    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. PostCodeForm 中创建了一个 Form1 的实例:

    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();

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

问题

我的问题是,我的文本框都没有更新给定值,但是当我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com