Chandan Pasunoori
Chandan Pasunoori

Reputation: 959

Implement Validation Where Textbox Gets Red Highlight On Failure

How does one make a textbox highlighted with red color when an event occurred like invalid number format in c#?

Upvotes: 3

Views: 9909

Answers (4)

ΩmegaMan
ΩmegaMan

Reputation: 31721

Its unclear why Skeet uses the event TextChanged when there is a Validating event and a Validated event.

What you want is the MaskedTextBox which can work with your number

See Overview of how to validate user input (Windows Forms .NET) and within that document Event-driven validation.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504062

It's not terribly clear what you mean, but it sounds like you want to do something like:

  • Hook up an event handler for whenever the text changes in a textbox
  • In that event handler, check whether the text can be parsed as a number, ideally using int.TryParse (rather than just parsing it and catching an exception)
  • Setting the foreground colour of the textbox to red or black, depending on whether the parsing attempt was successful

So something like:

textBox.TextChanged += (sender, args) => {
    int ignored;
    bool valid = int.tryParse(textBox.Text, out ignored);
    textBox.ForeColor = valid ? Color.Black : Color.Red;
};

(There may well be other rather more sophisticated ways of doinig this, including preventing the invalid input to start with... but for just changing the colour, this will work :)

Upvotes: 4

Mario
Mario

Reputation: 36567

Just adjust the property ForeColor of the control displaying the text based on the result of your validation, e.g. label1.ForeColor = isInputValid ? Color.Black : Color.Red; where isInputValid is a boolean value set wherever you do validation.

Upvotes: 1

JAiro
JAiro

Reputation: 6009

You could use the errorProvider. You can highligth the input or blink it, etc.

Take a look a this post in order to try it.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx#Y2680

Upvotes: 2

Related Questions