i want to make a textbox in my wpf application which will accept only integer values. if someone types characters between [a-z], the textbox will reject it. Thus it will not be displayed in the textbox
-
3I think this type of question has been asked before. See stackoverflow.com/questions/1346707/…Nipuna– Nipuna2011-03-08 12:58:30 +00:00Commented Mar 8, 2011 at 12:58
-
Why dont yoy use DataValidation in WPF which is built exactly for this kind of things? wpftutorial.net/DataValidation.htmlNVM– NVM2011-03-08 13:45:20 +00:00Commented Mar 8, 2011 at 13:45
Add a comment
|
5 Answers
In WPF, you can handle the KeyDown event like this:
private void MyTextBox_KeyDown(object sender, KeyDownEventArgs e)
{
e.Handled = true;
}
2 Comments
kyrylomyr
This will only prevent from entering text, but not from paste from clipboard.
David
copy/paste will always require a special tratment with post validation anyway, but the idea of doing a prefilter is probably better in this case. It can then be coupled with a post-validation. I would rather use the PreviewTextInput event instead of the KeyDOwn event though
You can add handle of the TextChanged event and look what was entered (need to check all text every time for preventing pasting letters from clipboard).
Also look a very good example of creating maskable editbox on CodeProject.
Comments
this simple code snippet should do the trick.. You might also want to check for overflows (too large numbers)
private void IntegerTextBox_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < Text.Length; i++)
{
int c = Text[i];
if (c < '0' || c > '9')
{
Text = Text.Remove(i, 1);
}
}
}
2 Comments
David
this does not prevent the user to type a "non-integer", it just removes it when it has been typed. Jogy's solution using the previewTextInput methods seems better. Your solution could be used as a post validation though (case of copy/paste)
Can Gencer
Yes you are right, sometimes you can see "flickering" where the text appears and then disappears when this code is used. I guess the best solution is a combination of both.