Windows窗体中的文本框验证

Ris*_*hri 6 .net c# validation textbox winforms

我想在提交表单之前验证用户是否始终在文本框中输入值.但是我放的支票允许用户输入空格并继续提交表格.因此,如果文本框中只有空格,则如何进行检查以使用户无法提交表单.

yon*_*236 7

您可以创建自己的自定义验证函数。这可能很幼稚,但不知何故它会起作用。

private bool WithErrors()
{
    if(textBox1.Text.Trim() == String.Empty) 
        return true; // Returns true if no input or only space is found
    if(textBox2.Text.Trim() == String.Empty)
        return true;
    // Other textBoxes.

    return false;
}

private void buttonSubmit_Click(object sender, EventArgs e)
{
    if(WithErrors())
    {
        // Notify user for error.
    }
    else
    {
        // Do whatever here... Submit
    }
}
Run Code Online (Sandbox Code Playgroud)


Ars*_*eny 5

在NET4.0中有一个不错的功能

 if(string.IsNullOrWhiteSpace(textBox1.Text))
{
   //raise your validation exception
}
else {
  //go to submit
}
Run Code Online (Sandbox Code Playgroud)