Reputation: 959
How does one make a textbox highlighted with red color when an event occurred like invalid number format in c#?
Upvotes: 3
Views: 9909
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
Reputation: 1504062
It's not terribly clear what you mean, but it sounds like you want to do something like:
int.TryParse
(rather than just parsing it and catching an exception)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
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
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