处理多个表单之间的数据

我正在制作一个生成PDF文件的程序。 在最后一代文件之前,我想让用户select编辑文件的一部分(即将创build的graphics的标题)。 当用户点击一个button导出PDF时,我希望它以新的forms显示出来。 这是我正在尝试做什么的概述…

private void button4_Click(object sender, EventArgs e) // Test PDF Code! { Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Length - 4)); NewPDF.Show(); if (NewPDF.Selected == true) { // Create PDF, open save file dialog, etc } } 

这里是通过这个button点击打开的窗体…

 public partial class Form2 : Form { public bool Selected { get; set; } public String GraphName { get; set; } public Form2(String FileName) { InitializeComponent(); textBox1.Text = FileName; GraphName = FileName; Selected = false; } public void button1_Click(object sender, EventArgs e) { GraphName = textBox1.Text; this.Selected = true; // After the button is selected I want the code written above to continue execution, however it does not! } } 

到现在为止,当我点击Form2中的button时,什么都没有发生,这两个表单之间的沟通还有一些我不了解的东西!

你应该改变你的Form2.GraphName像下面

 public String GraphName { get { return textBox1.Text } } 

然后更改您的新的Form2创建像下面,测试它,因为我没有通过VS运行这个,但应该工作:)

 private void button4_Click(object sender, EventArgs e) // Test PDF Code! { // why on earth were you doing .Text.ToString()? it's already string... Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Length - 4)); // show as a dialog form, so it will wait for it to exit, and set this form as parent NewPDF.ShowDialog(this); if (NewPDF.Selected == true) { // get the name from the other form string fileName = NewPDF.GraphName; // Create PDF, open save file dialog, etc } } 

你的问题的答案很简单。

 NewPDF.Show(); 

Show()不会暂停调用表单的执行。 因此,验证Selected属性(如果为true)下面的检查将永远不会正确执行,因为该检查在表单开始出现时已经达到并验证。 ShowDialog()会暂停执行并等待被调用的窗体关闭。

那一边 我会建议其他两种方式之一之间的沟通形式;

  1. 使用全局变量。 在公共模块中声明一个保存图形名称的变量。 调用对话框,要求用户使用ShowDialog()输入名称,因为这会暂停执行调用表单,直到调用表单返回结果。

     if(Form.ShowDialog() == DialogResult.OK) { // Save pdf, using title in global variable } 

    确保在Close()之前将DialogResult设置为被调用的形式。

  2. 将调用表单的实例变量传递给被调用的名称输入表单,并将其保存到构造函数中。 这样,如果将图名称属性公开为公共属性,则应该可以从关闭表单的代码中的被调用表单访问它,这是您的:

      public void button1_Click(object sender, EventArgs e) { callingFormInstance.GraphNameProperty = textBox1.Text; Close(); } 

希望有所帮助。 干杯!