Do / While在文本框中检查Null?

时间:2016-04-07 09:41:07

标签: c# wpf null

对于作业,我需要构建一个WPF C#表单,检查以确保在名为txtCityInput和textbox name txtStateInput的文本框中输入了一些内容。

我尝试了这样做/ while但它创建了无限循环(在MessageBox上)。

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

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

同样,我必须使用Do语句或Do / While语句来检查用户是否已输入"某些内容"进入这些文本框。

2 个答案:

答案 0 :(得分:2)

在这种情况下使用do-while循环的唯一方法是添加额外的if条件。

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); 
}

答案 1 :(得分:1)

你只需要这样做:

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

每次离开文本框时都应该再次触发事件。