When the textbox is null, the button will be off

3

When you type in textbox , the button will call, but when you do not have anything in textbox it will hang up. I was able to make the method of the button connect but I could not do the disconnect if the textbox is null

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (txt.Text == null)
    {
        bt.Enabled = false;
    }
    else
    {
        bt.Enabled = true;
    }
}
    
asked by anonymous 30.09.2017 / 16:30

4 answers

1

It will depend on the ideal and expected behavior for this, an example , if you do not want to blank space you 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 is still disabled, now if you want to also consider the spaces to enable the button just use Length of classe String

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

30.09.2017 / 18:41
1

This logic does not work because when TextBox is empty it has property Text as empty string ( "" ) and not null .

Just change your logic slightly:

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, you can even compress this logic a lot by doing this:

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

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

    
30.09.2017 / 16:52
0

Just by complementing Isac's response, it may be worth adding the Trim() method to the end if you do not want the button to be enabled with the keypad key:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bt.Enabled = txt.Text.Trim() != "";
}
    
30.09.2017 / 17:29
0

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

    
03.10.2017 / 22:02