Babaev
Babaev

Reputation: 55

How to validate textbox in C# WF?

I have two text boxes in windows form. Also one disabled button.

How I can do validation text box:

I tried this on event TextChange, but when I tried to enter value 43 I get notification, because event TextChange works after each typing symbols.

Code:

private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBox2.Text))
            {
                button6.Enabled = true;
            }
        }

Upvotes: 0

Views: 180

Answers (3)

Ivan Stoev
Ivan Stoev

Reputation: 205629

Neither TextChanged nor Leave events are appropriate for this. The proper event is called (surprise:-) Validating. You need to set e.Cancel = true if validation is wrong. More info: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx

Upvotes: 0

Johnie Karr
Johnie Karr

Reputation: 2822

If you don't want to validate each time a key is pressed but would rather validate when the user leaves the field, instead of hooking into the TextChanged event, hook into the Leave event.

private void textBox2_Leave(object sender, EventArgs e)
{
    button6.Enabled = !(string.IsNullOrEmpty(textBox2.Text)) && textBox2.Text.Length >= 5;

    if (!button6.Enabled)
    {
        textBox2.Focus();
    }
}

Upvotes: 1

Xiaoy312
Xiaoy312

Reputation: 14477

Update your event handle like this :

private void textBox2_TextChanged(object sender, EventArgs e)
{
    button6.Enabled = 
        !String.IsNullOrEmpty(textBox2.Text) && textBox2.Text.Length > 5
}

As for disabling the button on start up, you just set button6 to be disabled by default.

Or, invoke your validation in your constructor :

textBox2_TextChanged(null, null);

Upvotes: 0

Related Questions