0

我有 2 个表格。一个是主表单(form1),另一个是(form2)在我按下按钮时被调用。

当我按下一个按钮时,form2 会显示,它包含几个复选框和组合框。

我的问题是,如何存储或保存复选框状态和组合框选择,以便在关闭 form2 后可以在我的 form1 中使用它们(检查它们的状态/选择)?

这是一个基本示例:

Form2:

--I click on checkbox and the state changes:

checkbox1.Checked = true;

Form1:

private void button1_Click(object sender, EventArgs e)
{
if (checkbox1.Checked == true)
{
MessageBox.Show("Checkbox on form2 is checked")
}
}

提前致谢!

4

2 回答 2

1

Use Databinding and an object to pass around. The following example demonstrates how to achieve this without having to make anything static. Because the values become bound together if you do: state.IsChecked = false; that would also uncheck the checkbox on Form2.

Don't just add global variables, that's a large pain waiting to happen.

class Form1: Form
{
    private State state = new State();

    public Form1()
    {
        Load += HandleLoad;
    }

    public HandleLoad(object sender, EventArgs e)
    { 
        label1.DataBindings.Add("Text", state, "IsChecked"); // or just query state.IsChecked
    }
    public void someEvent_Handler()
    {
        Form2 form2 = new Form2();
        form2.Bind(state);
        form2.Show();
    }
}

class Form2: Form
{
    public void Bind(State state)
    {
        checkBox1.DataBindings.Add("Checked", state, "IsChecked");
    }
}

class State
{
    public bool IsChecked {get;set;}
}
于 2013-09-11T12:33:10.113 回答
0

在您当前的代码中,您每次都在创建新的表单实例,例如:

private void OpenForm2
{
    //open form2:
    Form2 form2 = new Form2();
    form2.ShowDialog(this);

    //read form2 values:
    if (form2.Checkbox1.Checked)
    {
        MessageBox.Show("Checkbox on form2 is checked")
    }
}

相反,使用一个全局实例并每次都显示它,这样可以保留它的状态:

Form2 form2 = new Form2();
private void OpenForm2
{
    //open form2:
    form2.ShowDialog(this);

    //read form2 values:
    if (form2.Checkbox1.Checked)
    {
        MessageBox.Show("Checkbox on form2 is checked")
    }
}
于 2013-09-11T12:25:51.367 回答