I am trying to validate multiple fields/Controls based on individual conditions. The issue is I have individual labels that indicate an error based on the specific control rather than a message box; is there a more efficient way to do this?
Here is the code:
if (txtPhone. Text. Length <= 0)
{
lblPhoneRequired.Visible = true;
}
else
{
lblPhoneRequired.Visible = false;
}
if (txtName. Text. Length <= 0)
{
lblNameRequired. Visible = true;
}
else
{
lblNameRequired. Visible = false;
}
Finally I tried wrapping this into a Public method like this:
public void validation() {
if (txtPhone. Text. Length <= 0)
{
lblPhoneRequired.Visible = true;
}
else
{
lblPhoneRequired.Visible = false;
}
if (txtName. Text. Length <= 0)
{
lblNameRequired. Visible = true;
}
else
{
lblNameRequired. Visible = false;
}
}
Then calling the method in a button click event but it does not work.
private void btnSample_Click(object sender, EventArgs e)
validation();
}
The is new territory so please bear with my ignorance:
Guy
You could shorten your code:
Note that this is not more or less efficient than your appoach, but it is less verbose and maybe more readable.
Of course you could also use a single control with a different error message:
But you should have a look at the
Validatingevent and theCausesValidationproperty which every control has.