James MacDonald
James MacDonald

Reputation: 65

C#: Forms and if statements

I have a newbie question that's been bugging me. I've been messing around with forms in visual studio. In the simple program I'm making, I want to disable/enable a button depending on whether a checkbox is ticked.

Can someone tell me why this code doesn't work? Specifically the if statement.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        Do_Check();
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        Do_Check();

    }

    private void Do_Check()
    {
        // button1.Enabled = checkBox1.Checked;

        if (checkBox1.Checked)
            button1.Enabled = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Blah blah");
    }


}

I've commented out one way of achieving the desired result. I'm just not sure why the if statement doesn't also work. Any help would be appreciated.

Upvotes: 1

Views: 88

Answers (1)

MetaColon
MetaColon

Reputation: 2871

Your button is only enabled if the checkBox1 is checked - but never disabled. Hence you should do something like this:

if (checkBox1.Checked)
    button1.Enabled = true;
else
    button.Enabled = false;

However, your commented solution with

button1.Enabled = checkBox1.Checked;

is way more elegant.

Upvotes: 3

Related Questions