ashiie
ashiie

Reputation: 11

C# How to disable button when the value is zero

I'm a beginner to C# programming and I really need some help :)

I made 2 buttons that will increment or decrement the value in the text box which is initially zero.

       private void bminus_Click(object sender, EventArgs e)
    {
        NUMBER--;
        textBox2.Text = NUMBER.ToString();
    }

    private void bplus_Click(object sender, EventArgs e)
    {
        NUMBER++;
        textBox2.Text = NUMBER.ToString();
    }

Will there be a way that the decrement button will be disabled if the value is 0 so that there won't be negative numbers? Thank you, I'd really appreciate anyone's help! :)

Upvotes: 1

Views: 581

Answers (5)

Magic Mick
Magic Mick

Reputation: 1523

All you need to do is add the following to the textBox2.TextChanged event handler and it should work with your current code.

private void textBox2_TextChanged(object sender, EventArgs e)
{
    int output;
    if (int.TryParse(textBox2.Text, out output))
    {
        bminus.Enabled = int.Parse(textBox2.Text) > 0;
    }
}

NOTE: No one here has specified checking for an integer so I added int.TryParse and int.Parse for this purpose.

Upvotes: 1

Oshawott
Oshawott

Reputation: 540

You can just directly insert logical state NUMBER not being 0 to your textBox2 Enabled property:

textBox2.Enabled = NUMBER != 0;

Or make a separate function from this:

private bool IsNotZero(double n)
{
    return n != 0;
}

then:

textBox2.Enabled = IsNotZero(NUMBER);

Upvotes: 1

gulshankundnani
gulshankundnani

Reputation: 1

Check the value using if condition. If the value is null or zero you can use button.enabled = false; code.if(value == zero || value == null) { button.enabled=false;} else {button.enabled = true;}

Upvotes: 0

b3nj4m1n
b3nj4m1n

Reputation: 524

private void bminus_Click(object sender, EventArgs e)
{
    NUMBER--;
    textBox2.Text = NUMBER.ToString();
    if(NUMBER == 0){
        bminus.Enabled = false;
    }
}

private void bplus_Click(object sender, EventArgs e)
{
    NUMBER++;
    textBox2.Text = NUMBER.ToString();
    bminus.Enabled = true;
}

That should do.

Upvotes: 3

Ryukote
Ryukote

Reputation: 794

Button have a property named Enabled which you can set to true or false based on your logic.

Upvotes: 0

Related Questions