2011-09-18 272 views
2

我在我的项目中有3个winform,在Form3上有一个复选框。我想要做的就是点击这个复选框,然后退出表单时,在Form1中进行相同的检查(无论是否选中)。我现有的代码如下,但它不会工作,我错过了一个诀窍的地方?谢谢。在表单之间传递数据

//Form3 

Form1 setDateBox = new Form1(); 
setDateBox.setNoDate(checkBox1.Checked); 

//Form1 

public void setNoDate(bool isChecked) 
{ 
    checkBox1.Checked = isChecked; 
} 
+3

你应该命名你的表单和控件。 – SLaks

+0

@Slaks,是的,我应该如何更改vs中的表单名称,以便在代码中使用名称Form1的所有内容都被更改? –

+0

当您重命名表单时,Visual Studio会自动重命名所有对它的引用。 – SLaks

回答

3

一对夫妇的方法:

1 -商店Form1的变量 “setDateBox” 作为Form3的一个类的成员,然后访问来自所对应的复选框的CheckedChanged事件处理程序 “setNoDate” 的方法:

private void checkBox1_CheckedChanged(object sender, EventArgs e) 
{ 
    setDateBox.setNoDate(checkBox1.Checked); 
} 

2 -如果您不希望setDateBox存储为一个类的成员,或者您需要更新不止一种形式,你可以像其左右的时间内Form3定义事件:

public event EventHandler<CheckedChangedEventArgs> 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<CheckedChangedEventArgs>(setDateBox.Form1_CheckBox1CheckedChanged); 

再火从Form3(事件后的复选框的选中状态改变):

private void checkBox1_CheckedChanged(object sender, EventArgs e) 
{ 
    if(CheckBox1CheckedChanged != null) 
     CheckBox1CheckedChanged(this, new CheckedChangedEventArgs(checkBox1.Checked)); 
} 

希望这会有所帮助。

2

checkBox1Form3一员,所以从Form1不能引用这种方式。

,你可以:

  • 创建一个单独的类大家分享当中的形式,它可将影响整个应用价值
  • 使Form3.checkBox1公开可见的,所以您可以通过myForm3Instance.checkBox1
2
引用它

在包含复选框的表单的设计器中,将其设置为内部或公共。然后,您可以从窗体对象访问控件。它是一种快速和肮脏的方式来实现,但它可能会解决您的问题。

ex 
In form1.designer.cs 
existing 
private CheckBox checkbox1; 

new one 

internal CheckBox checkbox1; or 
public CheckBox checkbox1; 
2

您正在创建Form1的一个新实例,而不是引用它的现有实例。

Form1 setDateBox = (Form1)this.Owner 

这应该解决您的问题。