开发者

Change the state of a checkbox on Form2 and keep the state

All I am trying to do is to change the state of checkbox on form2, and keep the state after pression OK. I have form1 which is my main form and it only has one Strip menu. The code for form1 is as follow:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using 开发者_运维百科System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void dialogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 dialog = new Form2();

            dialog.ShowDialog();
        }
    }
}

The Form2 only has one checkbox and one OK button.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void OK_Click(object sender, EventArgs e)
        {

            if (cbxForm2.Checked == true)
            {
                cbxForm2.Checked = true;
            }
        }
    }
}

How can I change my code so when I go back on the menu the state of the combo box is as I left it?


You are creating a new Form2 every time:

private void dialogToolStripMenuItem_Click(object sender, EventArgs e)
{
    // the 'new' keyword means you are creating an entirely new instance
    Form2 dialog = new Form2();
    dialog.ShowDialog();
}

This new instance has no idea what any previous instances looked like, so you need to store the state of the CheckBox and assign the value when you open Form2.

public partial class Form1 : Form
{
    // backing field to store the state
    bool checkBoxChecked;

    public Form1()
    {
        InitializeComponent();
    }

    private void dialogToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form2 dialog = new Form2();

        // assign the state
        dialog.CheckBoxChecked = this.checkBoxChecked;
        dialog.ShowDialog();

        // save the state
        this.checkBoxChecked = dialog.CheckBoxChecked;
    }
}

You also need to add a property on Form2 so you can retrieve the state:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public bool CheckBoxChecked
    {
        get { return cbxForm2.Checked; }
        set { cbxForm2.Checked = value; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜