简体   繁体   中英

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 . code are required in loop using foreach in case of having multiple textBox on a form.

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:

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. 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:

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

Sample 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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