Hi,
i need a validation to check whether key pressed down is numeric or not. i tried with different code but they cant help me out.In the textbox if the user press Shift+numbers it displays special charcters like !,@,#...... I need to validate the Shift + key down event. Please find the sample code i tried below and help me out.
private void txtNumericTextbox_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.Key < Key.D0 || e.Key > Key.D9)
{
if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
if (e.Key != Key.Back)
{
txtNumericTextbox_.BorderBrush = new SolidColorBrush(Colors.Red);
lblErrorMessage.Visibility = Visibility.Visible;
lblErrorMessage.Text = "Please Enter Numbers Only";
}
else
{
txtNumericTextbox_.BorderBrush = new SolidColorBrush(Colors.DarkGray);
lblErrorMessage.Visibility = Visibility.Collapsed;
lblErrorMessage.Text = "";
}
}
}
Thanks,
Vijay
Loading
Pravin MorePosted Nov 20, 2011, 11:25 PM
You can use the ModifierKeys property on control to determine if the shift key is being held.
if (Control.ModifierKeys == Keys.Shift )
{ ... }
and other code is correct for detecting number.
Thanks,
Pravin.
Riddhi ValechaPosted Jan 21, 2013, 3:49 AM
The code for numbers worked out....
Try this for alphabets -
if (((e.Key > Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back || e.Key == Key.Tab))
e.Handled = true;
else
{
e.Handled = false;}
Pradip PandeyPosted Nov 27, 2012, 5:32 AM
If it helped, please mark this as Accepted Answer.
Riddhi ValechaPosted Nov 27, 2012, 5:17 AM
Thanks a lot............
yes... this code worked out for me !!!!!
Pradip PandeyPosted Nov 26, 2012, 2:47 AM
Use this to accept only numeric values. Event you can choose textBox1_KeyDown
Use this to accept only characters. Event you can choose textBox1_KeyPress
Hope it will help.
Riddhi ValechaPosted Nov 26, 2012, 12:43 AM
Please help me out ... I am having the same problem...
There are 2 textboxes:
1st textbox - should accept only numeric values and 2nd should accept only characters value..
I am not getting how to do this...
Please help...
Thanks in advance !!
Priya LingePosted Nov 21, 2011, 12:11 AM
Please try this,
private void usertext_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Shift)
{
e.Handled = true;
MessageBox.Show("Please Enter Numbers Only");
}
if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9))
{
if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
if (e.Key != Key.Back)
{
e.Handled = true;
}
}
}
}
Hope this will help you.
Thanks.