I am creating a windows store app in visual studio 12 , I am using c# language ,i have a text box ,but how to make it to accept only numbers ,if user tries to entry any other value than the number it should show an error message
In addition to the other answers, as you're writing a Windows Store App and will most likely be dealing with a virtual keyboard, you can make sure that you get a suitable keyboad view by setting the InputScope
of the TextBox
correctly (MSDN link here)
<TextBox InputScope="Number" .../>
There are a bunch of useful InputScope
values described here.
Note that you will still need to do validation as described in the other answers, because you have to cater for the user overriding the displayed keyboard type or having an attached physical keyboard. I would do it with a KeyDown
event handler, like so
private void TextBox_KeyDown_Number(object sender, KeyRoutedEventArgs e)
{
if ((uint)e.Key >= (uint)Windows.System.VirtualKey.Number0
&& (uint)e.Key <= (uint)Windows.System.VirtualKey.Number9)
{
e.Handled = false;
}
else e.Handled = true;
}