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 MoreRank #1,419 · 1.2K reputationPosted Nov 20, 2011, 6:25 PM EST
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.
Priya LingeRank #785 · 2.9K reputationPosted Nov 20, 2011, 7:11 PM EST
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.
Riddhi ValechaRank #794 · 2.9K reputationPosted Nov 25, 2012, 7:43 PM EST
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 !!
Pradip PandeyRank #452 · 5.6K reputationPosted Nov 25, 2012, 9:47 PM EST
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 ValechaRank #794 · 2.9K reputationPosted Nov 27, 2012, 12:17 AM EST
Thanks a lot............
yes... this code worked out for me !!!!!
Pradip PandeyRank #452 · 5.6K reputationPosted Nov 27, 2012, 12:32 AM EST
If it helped, please mark this as Accepted Answer.
Riddhi ValechaRank #794 · 2.9K reputationPosted Jan 20, 2013, 10:49 PM EST
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;}