I want to create a TextBox (WinForms) that only accepts possitive or negative numbers and any number of character 'k' at the end, I think the pattern is ^-?[0-9]+k*$
I want to prevent the user from writing any character that does not match withe that expression. This is the class that I have implemented:
public class NumTextBox : TextBox {
private Regex regex;
public NumTextBox() : base() {
regex = new Regex(@"^-?[0-9]+k*$");
}
protected override void OnKeyPress(KeyPressEventArgs e) {
String s = Text + e.KeyChar; // current text + new character
if (!regex.Match(s).Success) {
e.Handled = true;
} else {
e.Handled = false;
}
base.OnKeyPress(e);
}
}
}
With that, the TextBox does not allow you to write characters at the beginning of the text, but it allows you to write them after some digit, I mean:
asd -> Not allowed
123asd -> allowed, this shouldn't be allowed
I have also tried to add the end character to s but it neither works.
Edit:
I have seen in the debugger that the string s has the new character at the end.
Edit 2
Why don't you just TryParse the TextBox's Text value?
Because I want to prevent the user to be able to write not allowed characters, according to the regex.
The code has some other problems too : 1. It should not work if user start to enter a negative number because (-) itself is not matched. 2. what if the text is 123 and user click between 1 and 2 and then press k ?( keypress is not a good place for this)
1: I think you are right, but I prefer to solve this problem now and take care of that later.
2: Letter 'k' shouldn't be allowed between digits, only at the end of the number.
If you debug your code, is the regex matching and stepping into e.Handled=true, or not? Also, OnTextChanged might be a better method to override.
If I debug the code, the regex matchs (says it's correct) wrong strings (f.e. 123asd), so it doesn't step into
e.Handled = true.I think you are referring to override
OnTextChangedand delete the last char written if it doesn't match with the regex, don't you? In that case, a problem that I've seen is that the text pointer returns to the beginning.
TryParsethe TextBox'sTextvalue? - Kenneth K.