Reputation: 33
I am trying to apply error providers to a text box,
The user cannot enter more than 25 characters The textbox cannot be left blank
private void txtNameandSurn_TextChanged(object sender, EventArgs e)
{
txtNameandSurn.MaxLength = 25;
if (txtNameandSurn.Text == "")
{
txtNameandSurn.BackColor = Color.White;
errorProvider1.SetError(txtNameandSurn, "Cannot be blank!");
}
else
{
txtNameandSurn.BackColor = Color.Red;
errorProvider1.SetError(txtNameandSurn, "");
}
if (txtNameandSurn.Text.Length >= txtNameandSurn.MaxLength)
{
errorProvider1.SetError(txtNameandSurn, "Cannot input more than 25 characters!");
}
else if (txtNameandSurn.Text.Length < txtNameandSurn.MaxLength)
{
errorProvider1.SetError(txtNameandSurn, "");
}
}
The issue I have is with the character input, the error provider shows up but when i press another key the icon for the errorprovider disappears but the character is not inputted which is good. How do I keep the error provider icon showing?
Upvotes: 0
Views: 218
Reputation: 2868
For great readability and flexibility for adding new rules, I prefer this syntax. Note that this also lends itself to creating reusable sets of rules for specific data types. This untested code should solve your problem with the errorProvider, if I understood it.
class Rule
{
public Func<string, bool> Test { get; set; }
public string Message { get; set; }
}
private void txtNameandSurn_TextChanged(object sender, EventArgs e)
{
var rules = new List<Rule>()
{
new Rule() { Test = s => !String.IsNullOrEmpty(s), Message="String cannot be blank." },
new Rule() { Test = s => (s.Length <= txtNameandSurn.MaxLength), Message="String cannot be longer than " + txtNameandSurn.MaxLength },
new Rule() { Test = s => !s.Contains("#"), Message = "String cannot contain a hash character." }
};
var isValid = rules.All(r => r.Test(txtNameandSurn.Text));
string[] message;
if (!isValid)
{
message = rules.Where(r => r.Test(txtNameandSurn.Text) == false).Select(r => r.Message);
}
errorProvider1.SetError((message.Length > 0) ? (string.Join(';', message)) : "");
}
Upvotes: 1
Reputation: 14432
You should rewrite your conditions in a logical manner. Every case where there is not a correct input should have it's definition and have the correct error set. In the other case (input is correct), remove the error. Simplified it should look like this:
if (String.IsNullOrEmpty(textBox1.Text))
{
errorProvider1.SetError(textBox1, "Cannot be blank!");
}
else if(textBox1.Text.Length >= textBox1.MaxLength)
{
errorProvider1.SetError(textBox1, "Cannot input more than 25 characters!");
}
else
{
errorProvider1.SetError(textBox1, "");
}
This way, you can add more conditions easiliy. If you want for example that the tekst doesn't contain a #
, simply add following statement:
if(textBox1.Contains("#"))
{
errorProvider1.SetError(textBox1, "Cannot contain a '#'!");
}
Upvotes: 1