Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Hide and Show a button with if statements c#

I am trying to make a button visible = false if a quantity in a text box is less than or equal to 0. The problem I am having is that you have to click the button in order to activate the function.

Here is my code so far

int quantity = int.Parse(textBox33.Text);

if (quantity <= 0)
    button13.Visible = false;

if (quantity > 0)
    button13.Visible = true;

do I have to disable the visibility of the text box beforehand?

like image 783
D McCracken Avatar asked Nov 24 '25 23:11

D McCracken


1 Answers

At first you should encapsulate the code to update the button in a specific method:

private void UpdateButton13()
{
    button13.Visible = quantity > 0; // no need for if/else
}

Then you can call this from every event after which the button should be updated. From your comments it seems you want to update that button

  • at Form load and
  • when the text in textBox33 has been changed.

So for example:

public class YourForm : Form
{
    public YourForm()
    {
        InitializeComponents();

        // register event handlers:
        Load += YourForm_Load;
        textBox33.TextChanged += textBox33_TextChanged;
    }

    private void YourForm_Load(object sender, EventArgs e)
    {
        UpdateButton13();
    }
    private void textBox33_TextChanged(object sender, EventArgs e)
    {
        UpdateButton13();
    }

    private void UpdateButton13()
    {
        button13.Visible = quantity > 0; // no need for if/else
    }
}

Of course you can also create and register the event handlers in the designer window, without having to write the code in the constructor yourself.


The code above may now seem a little redundant (same code in two methods and a one-line method). But I assume that you want to do further things on loading the form and on changing text, and maybe you want to call UpdateButton13 from other parts of your code, too. So encapsulating here is good style (imho) to avoid problems for further development.

like image 60
René Vogt Avatar answered Nov 26 '25 11:11

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!