Reputation: 4443
How to validate text in textbox control in winforms?
I have a control, where user have to put string, like "13:55". I want to show MessageBox, when this value will be diffrent, than "XX:YY".
How to do it?
In asp.net it was so easy to make, but how to implement it on winforms?
Upvotes: 1
Views: 6228
Reputation: 17973
You could also use an ErrorProvider instead of popping up a messagebox. An example is available on msdn for the ErrorProvider class. Basically you subscribe to the Validated event
this.nameTextBox1.Validated += nameTextBox1Validated;
and then check if the value is valid
private void nameTextBox1Validated(object sender, EventArgs e) {
if(isNameValid()) {
// clear error
nameErrorProvider.SetError(nameTextBox1, String.Empty);
}
else {
// set some helpful message
nameErrorProvider.SetError(nameTextBox1, "Invalid value.");
}
}
private bool isNameValid() {
// The logic for determining if a value is correct
return nameTextBox1.Text == "hello";
}
the error provider can be created like this
ErrorProvider nameErrorProvider = new ErrorProvider();
nameErrorProvider.SetIconAlignment(nameTextBox1, ErrorIconAlignment.MiddleRight);
nameErrorProvider.SetIconPadding(nameTextBox1, 2);
nameErrorProvider.BlinkRate = 1000;
nameErrorProvider.BlinkStyle = ErrorBlinkStyle.AlwaysBlink;
Upvotes: 0
Reputation:
You should take a look at C# Regex
Match match = Regex.Match(input, "^\d\d:\d\d$"));
if (!match.Success) MessageBox.Show("Error");
Upvotes: 0
Reputation: 25820
Check out the MaskedTextBox if you don't want to have to validate in the first place.
var l_control = new MaskedTextBox();
l_control.Mask = "00\:00";
If you want to make the first digit optional:
l_control.Mask = "90\:90";
Otherwise, you could use a regular expression. 4 digits separated by a colon would be: @"^\d{2}:\d{2}$"
. (The @
symbol prevents C# from treating '\' as an escape character - nothing unique to regex.)
Upvotes: 4
Reputation: 73554
There are three validation videos at http://windowsclient.net/learn/videos.aspx that will walk you through the whole process.
But using a Masked Textbox might be easier, depending on what you are collecting for data.
Heck, for what you're doing, you could be really safe and use two NumericUpDown controls and not have to deal with the validation at all.
Upvotes: 1