Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用表单构造函数中的foreach循环进行用户输入验证_C#_.net_Winforms_Validation - Fatal编程技术网

C# 使用表单构造函数中的foreach循环进行用户输入验证

C# 使用表单构造函数中的foreach循环进行用户输入验证,c#,.net,winforms,validation,C#,.net,Winforms,Validation,我正在尝试在文本框中使用此自定义方法进行用户输入验证。但我觉得这种方法缺少一些东西。现在,如果验证失败,请使用“无法移动到下一个文本框”。这是好事还是坏事 private void textBox_Validating(object sender, CancelEventArgs e) { TextBox currenttb = (TextBox)sender; if (currenttb.Text == "") { MessageBox.Show(str

我正在尝试在文本框中使用此自定义方法进行用户输入验证。但我觉得这种方法缺少一些东西。现在,如果验证失败,请使用“无法移动到下一个文本框”。这是好事还是坏事

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if (currenttb.Text == "")
    {
        MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
        e.Cancel = true ;
    }

    else
    {
        e.Cancel = false;
    }
}
使用表单构造函数中的foreach循环将处理程序添加到文本框:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}
foreach(this.Controls.OfType()中的文本框tb,其中(x=>x.CausesValidation==true))
{
tb.Validating+=文本框\正在验证;
}

如何使用,如果验证失败,它将显示感叹号

我认为如果弹出太多的消息框,将是一种糟糕的用户体验。也许您应该考虑使用标签在每个文本框旁边显示错误消息。在您的程序中,如果文本框为空,我甚至无法通过单击关闭按钮来关闭窗口