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 characters like !,@,#
...... I need to validate the Shift + key down event
.
//Code
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 = "";
}
}
}
}
}
How can I achieve that?
You can use the ModifierKeys property on control to determine if the shift key is being held.
//Code
Use this to accept only numeric values. Event you can choose textBox1_KeyDown nonnumberenter = false;
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
nonnumberenter = true;
string abc = "Please enter numbers only.";
DialogResult result1 = MessageBox.Show(abc.ToString(), "Validate numbers", MessageBoxButtons.OK);
}
}
}
if (Control.ModifierKeys == Keys.Shift)
{
nonnumberenter = true;
string abc = "Please enter numbers only.";
DialogResult result1 = MessageBox.Show(abc.ToString(), "Validate numbers", MessageBoxButtons.OK);
}
Use this to accept only characters. Event you can choose textBox1_KeyPress
if (Char.IsNumber(e.KeyChar) || Char.IsSymbol(e.KeyChar) || Char.IsWhiteSpace(e.KeyChar) || Char.IsPunctuation(e.KeyChar))
{
MessageBox.Show("Only Char are allowed");
e.Handled = true;
}
Hope this helps.
You can use text box key press event
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) )
{
e.Handled = true;
}
}
I was looking for the same thing: . 。 However, I did not find any e.KeyCode
on my _KeyDown
event, so I adapted Kumar's code to suit my needs, and am sharing with you, should it be more fitting to you: Use e.Handled = true
to cancel the input of that character.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.NumPad0:
case Key.NumPad1:
case Key.NumPad2:
case Key.NumPad3:
case Key.NumPad4:
case Key.NumPad5:
case Key.NumPad6:
case Key.NumPad7:
case Key.NumPad8:
case Key.NumPad9:
case Key.D0:
case Key.D1:
case Key.D2:
case Key.D3:
case Key.D4:
case Key.D5:
case Key.D6:
case Key.D7:
case Key.D8:
case Key.D9:
break;
default:
e.Handled = true;
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.