简体   繁体   English

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

[英]TextBox validation error with focus and backColor change

I have a simple calculator application in which I used two textBox , the first is for entering first value and second is for second value the issue is with the code which will turn the focus on an empty textBox also will change its backColor .我有一个简单的计算器应用程序,其中我使用了两个textBox ,第一个用于输入第一个值,第二个用于输入第二个值,问题在于代码将焦点转向空textBox也会改变其backColor code are required in loop using foreach in case of having multiple textBox on a form.如果表单上有多个textBox ,则需要使用foreach在循环中使用代码。

The code for empty textbox error is written in the result click button as:空文本框错误的代码写在结果点击按钮中:

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

probably you are looking for this:可能你正在寻找这个:

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

and this Will Help you validate all the TexBox Controls:这将帮助您验证所有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;
         }
    }
}

UPDATE: I modified == comparison with string method IsNullOrEmpty() plus I called an extra method Trim() that will basically remove all the leading and trailing whitespaces from input.更新:我修改了==与字符串方法IsNullOrEmpty()比较,加上我调用了一个额外的方法Trim() ,它基本上会从输入中删除所有前导和尾随空格。 So, if the user has inputted only blank spaces, it will remove them then see if it becomes empty or not.因此,如果用户只输入了空格,它将删除它们,然后查看它是否为空。

As written in my comment, iterating the form control collection:正如我的评论中所写,迭代表单控件集合:

Sample 1:示例 1:

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

Sample 2:示例 2:

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

Sample 3:示例 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");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM