Nutella
Nutella

Reputation: 1

Second checkbox depends from another checkbox

I want make second checkbox invisible while first checkbox isn't "checked". In other case i want check my first checkbox and the second should be clickable. How can i do it?

My example doesn't work:

if (FirstCheckBox.Checked == true)
{
    SecondCheckBox.Visible = true;
}
else if (FirstCheckBox.Checked == false)
{
    SecondCheckBox.Visible = false;
}

Upvotes: 0

Views: 128

Answers (1)

v.slobodzian
v.slobodzian

Reputation: 493

You should use the CheckedChanged event. For example:

public Form1()
{
    InitializeComponent();
    checkBox1.CheckedChanged += CheckBox1_CheckedChanged;
    checkBox2.Enabled = false;
}

//When happens some change in a checkBox1
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBox1.Checked)
        checkBox2.Enabled = true;
    else
        checkBox2.Enabled = false;
}

The same using lambda expressions:

public Form1()
{
    InitializeComponent();
    checkBox2.Enabled = false;
    checkBox1.CheckedChanged += (s, e) => checkBox2.Enabled = checkBox1.Checked;
}

Upvotes: 1

Related Questions