在表单之间传递数据
我的项目中有3个winforms,而Form3上有一个复选框。 我希望能够做的是单击此复选框,然后退出表单时,在Form1中的那个上进行相同的检查(无论是否选中)。 我现有的代码如下,但它不起作用,我在某处错过了一个技巧吗? 谢谢。
//Form3 Form1 setDateBox = new Form1(); setDateBox.setNoDate(checkBox1.Checked); //Form1 public void setNoDate(bool isChecked) { checkBox1.Checked = isChecked; }
几种方法:
1 –将Form1变量“setDateBox”存储为Form3的类成员,然后从复选框CheckedChanged事件处理程序访问“setNoDate”方法:
private void checkBox1_CheckedChanged(object sender, EventArgs e) { setDateBox.setNoDate(checkBox1.Checked); }
2 –如果您不希望将setDateBox存储为类成员,或者您需要更新多个表单,则可以在Form3中定义一个事件,如下所示:
public event EventHandler CheckBox1CheckedChanged; ... public class CheckedChangedEventArgs : EventArgs { public bool CheckedState { get; set; } public CheckedChangedEventArgs(bool state) { CheckedState = state; } }
在Form1中为事件创建一个处理程序:
public void Form1_CheckBox1CheckedChanged(object sender, CheckedChangedEventArgs e) { //Do something with the CheckedState MessageBox.Show(e.CheckedState.ToString()); }
创建表单后分配事件处理程序:
Form1 setDateBox = new Form1(); CheckBox1CheckedChanged += new EventHandler(setDateBox.Form1_CheckBox1CheckedChanged);
然后从Form3中触发事件(在复选框的选中状态更改时):
private void checkBox1_CheckedChanged(object sender, EventArgs e) { if(CheckBox1CheckedChanged != null) CheckBox1CheckedChanged(this, new CheckedChangedEventArgs(checkBox1.Checked)); }
希望这可以帮助。
checkBox1
是Form3
的成员,因此从Form1
您不能以这种方式引用它。
你可以:
- 创建一个单独的类,您在表单中共享,保留影响整个应用程序的值
- 使
Form3.checkBox1
公开可见,因此您可以通过myForm3Instance.checkBox1
引用它
在包含复选框的表单的设计器中,将其设置为内部或公共。 然后,您可以从窗体对象访问该控件。 它是一种快速而肮脏的方式,但它可以解决您的问题。
ex In form1.designer.cs existing private CheckBox checkbox1; new one internal CheckBox checkbox1; or public CheckBox checkbox1;
您正在创建Form1的新实例,而不是引用它的现有实例。
Form1 setDateBox = (Form1)this.Owner
这应该可以解决你的问题。