Reputation: 27
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 !!
}
Upvotes: 0
Views: 3796
Reputation: 4547
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.
Upvotes: 2
Reputation: 2060
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");
}
}
}
Upvotes: 0