带有焦点和背景颜色更改的文本框验证错误

TextBox validation error with focus and backColor change

我有一个简单的计算器应用程序,其中我使用了两个 textBox ,第一个用于输入第一个值,第二个用于输入第二个值问题在于代码会将焦点转移到空 textBox也会改变它的backColor。 在表单上有多个 textBox 的情况下,使用 foreach 在循环中需要代码。

空文本框错误的代码在结果点击按钮中写为:

if(textBox1.Text=="" || textBox2.Text=="")
{
 MessageBox.Show("Error","Error");
 //Required codes !!
}

可能您正在寻找这个:

if(string.IsNullOrEmpty(textbox1.Text.Trim()))
{
   textBox1.Focus();
   textBox1.BackColor = Color.Red;
} 
else if(string.IsNullOrEmpty(textbox2.Text.Trim()))
{
   textBox2.Focus();
   textBox2.BackColor = Color.Red;
} 

这将帮助您验证所有TexBox控件:

foreach (Control control in this.Controls)
{
    if (control.GetType() == typeof(TextBox))
    {
         TextBox textBox = (TextBox)control;
         if (string.IsNullOrEmpty(textBox.Text.Trim()))
         {
             textBox.Focus();
             textBox.BackColor = Color.Red;
         }
    }
}

更新: 我修改了 == 与字符串方法 IsNullOrEmpty() 的比较,另外我调用了一个额外的方法 Trim(),它基本上会删除所有来自输入的前导和尾随空格。所以,如果用户只输入了空格,它会删除它们然后看它是否变空。

正如我在评论中所写,迭代表单控件集合:

示例 1:

 foreach (Control co in this.Controls)
 {
     if (co.GetType() == typeof(TextBox))
     {
          MessageBox.Show(co.Name);
     }
 }

示例 2:

foreach (Control co in this.Controls)
{
    if (co.GetType() == typeof(TextBox))
    {
        TextBox tb = co as TextBox;
        MessageBox.Show(co.Name + "/" + co.Tag);
    }
}

示例 3:

foreach (Control co in this.Controls)
{
    TextBox tb = co as TextBox;
    if (tb != null)
    {
        if (!String.IsNullOrWhiteSpace((string)tb.Tag))
        {
            MessageBox.Show(co.Name + "/" + co.Tag);
        }
        else
        {
            MessageBox.Show(co.Name + " ... without tag");
        }
    }
}