i am using a French keyboard. On top keyboard there are keys like &,é,",',(,-,è,_,ç,à to use it as a number i have to press shift or turn the capslock on.
maximum number that i can put in text box in 24.
with capLock on : i can put numbers. with capLock off : i cannot put numbers using shift.
also i can put values like &,é,",',(,-,è,_,ç,à in the text box.
public class NumericalTextBox : TextBox
{
private int MaxValue;
public NumericalTextBox()
{
}
public NumericalTextBox(int max_value)
{
MaxValue = max_value;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
e.SuppressKeyPress = true;
}
}
}
if (Control.ModifierKeys == Keys.Shift)
{
e.SuppressKeyPress = true;
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (MaxValue >= 0 && !char.IsControl(e.KeyChar) && char.IsDigit(e.KeyChar))
{
try
{
string s = this.Text + e.KeyChar;
int x = int.Parse(s);
if (x >= MaxValue)
e.Handled = true;
}
catch
{
//e.Handled = true;
}
}
base.OnKeyPress(e);
}
}
}
If you can, use the NumericUpDown-Control instead. It provides you the wished behaviour (filtering non-numeric values).
However, if you must use a textbox, the comment of Shtako-verflow points to the answer.
The top answer's code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments