i need a code, for registrationform. The person that wants to registrate need to fill all textboxes. i want that its working with :
if (..........)
{
usernLbl.ForeColor = Color.Red;
nameLbl.ForeC开发者_StackOverflow中文版olor = Color.Red;
ageLbl.ForeColor = Color.Red;
countryLbl.ForeColor = Color.Red;
passwordLbl.ForeColor = Color.Red;
}
else
{
// save xml
}
Tnx
I solved it by doin this :
if (string.IsNullOrEmpty(ageTxb.Text))
{
ageLbl.ForeColor = Color.Red;
}
if (string.IsNullOrEmpty(usernameTxb.Text))
{
usernLbl.ForeColor = Color.Red;
}
if (string.IsNullOrEmpty(nameTxb.Text))
{
nameLbl.ForeColor = Color.Red;
}
if (string.IsNullOrEmpty(countryTxb.Text))
{
countryLbl.ForeColor = Color.Red;
}
if (string.IsNullOrEmpty(passwordTxb.Text))
{
passwordLbl.ForeColor = Color.Red;
}
private static bool NotEmpty(params TextBox[] textBoxes)
{
bool valid = true;
foreach(var box in textBoxes)
{
if (String.IsNullOrEmpty(box.Text))
{
box.ForeColor = Color.Red;
valid = false;
}
}
return valid;
}
So a sample call would be
if (NotEmpty(textBox1, textBox2, textBox3)
{
//save xml
}
You'll want to do it control by control so you can highlight only the incorrect ones (for example):
usernLbl.ForeColor = ValidateUsername(usrnTxtbox.Text);
nameLbl.ForeColor = ValidateName(nameTxtbox.Text);
public Color ValidateUsername(string username)
{
if(<first BAD condition>)
{
return Color.Red;
}
//etc.
return Color.Black;
}
And the same for the rest. The nice part of that is you can separate the validation code into a helper class so that your code stays readable.
You want to check if there is an text inside the textboxes?
if(string.IsNullorEmpty(usernTb.Text))
{
usernLbl.ForeColor = Color.Red;
}
If you have a ton of text controls you could do something like this
foreach (Control c in parent.Controls)
{
var tb = c as TextBox;
if (tb != null)
{
//do your validation
if (string.IsNullOrEmpty(tb.Text))
{
tb.ForeColor = Color.Red
}
}
}
Are you trying to validate the user input? Which kind of presentation are you using? WPF? Windows Forms? ASP.NET?
Anyway if you want to check that every textbox is filled try to use string.IsNullOrEmpty(string)
:
bool validated = Validate(ageTB, nameTB, countryTB, etc);
if (validated)
{
// Save XML
}
else
{
// Show error
}
private bool Validate(params TextBox[] textboxes)
{
foreach (TextBox tb in textboxes)
{
if (string.IsNullOrEmpty(tb.Text))
return false;
}
return true;
}
EDIT: If you're working with .NET Framework 4.0 use string.IsNullOrWhitespace
method.
精彩评论