概述:
将数据从一种形式传递到另一种形式。
这是一个WinForm应用程序,它有两个表单,名为form1
和PostCodeForm
。我需要将数据从短期格式PostcodeForm
传递回Form1到clickEvent
,然后关闭表单。这些值存储在dataTable
类的PostcodeSearch
中,并且可以访问它们:
在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;
在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时,我可以看到值,所以我不知道为什么TextBoxes没有显示值,因为我一直从表单传递数据以这种方式形成。
答案 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();