Nate E.
Nate E.

Reputation: 134

Do/While to check for Null in textbox?

For an assignment I need to build a WPF C# Form that checks to make sure something has been enter in the textbox named txtCityInput and textbox name txtStateInput.

I tried this do/while but it creates and infinite loop (on the MessageBox).

    private void txtCityInput_Leave(object sender, EventArgs e)
    {
        do
        {
            txtCityInput.Focus();
            MessageBox.Show("Enter a City");
        }

        while (txtCityInput.Text.Length == 0);
    }

Again it I have to use either a Do Statement or Do/While statement to check that the user has entered "something" into these textboxes.

Upvotes: 0

Views: 247

Answers (2)

Orkun Bekar
Orkun Bekar

Reputation: 1441

The only way of using do-while loop for that situation is adding an extra if condition.

private void txtCityInput_Leave(object sender, EventArgs e)
{
    do
    {
        if (txtCityInput.Text.Length == 0)
        {
            txtCityInput.Focus();
            MessageBox.Show("Enter a City");
        }
        else
        {
            break;
        }
    }
    while (!txtCityInput.Focused); 
}

Upvotes: 2

Dan Dumitru
Dan Dumitru

Reputation: 5423

You just need to do:

private void txtCityInput_Leave(object sender, EventArgs e)
{
    if (txtCityInput.Text.Length == 0)
    {
        txtCityInput.Focus();
        MessageBox.Show("Enter a City");
    }
}

The event should be triggered again each time he leaves the textbox.

Upvotes: 1

Related Questions