When the textbox is null, the button will be off

Asked

Viewed 449 times

3

When to write in the textbox, the button will turn on, but when you have nothing on textbox will turn off. I was able to make the button method turn on but could not do the turn off if the textbox is void

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (txt.Text == null)
    {
        bt.Enabled = false;
    }
    else
    {
        bt.Enabled = true;
    }
}

4 answers

1

That logic doesn’t work because when the TextBox is empty she has the property Text as empty string ("") and not null.

So just slightly change your logic:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (txt.Text == "") //agora com "" de string vazia
    {
        bt.Enabled = false;
    }
    else
    {
        bt.Enabled = true;
    }
}

In fact it can even compress this logic enough doing so:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bt.Enabled = txt.Text != "";
}

Note that in this last version Enabled receives the value of the comparison txt.Text != "" and so it will be directly the true or false who intends.

1


It will depend on the ideal and expected behavior for this, an example, if you don’t want to space blank will have to use string.Isnullorwhitespace, example:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    button1.Enabled = !(string.IsNullOrWhiteSpace(textBox1.Text));
}

this causes you to put space without any letter, will not consider and the button remains disabled, now if you want to consider also the spaces to enable the button just use property Length of classe String

private void textBox1_TextChanged(object sender, EventArgs e)
{
    button1.Enabled = textBox1.Text.Length > 0;
}

References

0

Complementing what the friend said, using Trim can improve your code as it will check the text completely

0

Just by complementing the Isac response, it might be interesting to add the method Trim() at the end, if you do not want the button to be enabled only with the space key of the keyboard:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bt.Enabled = txt.Text.Trim() != "";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.