MSDN上提供了方案: 如何:创建数字文本框,它重载了TextBox类。
当然,你也可以重写该控件而不继承任何Control类,那样在外观上效果更好。
MSDN上主要是做了非数字的处理,数字,逗号(可以指定),小数点,退格键和空格键是被允许输入的,当然也可以添加Ctrl和Alt组合键。当然,如果要使用还需要做进一步的处理,比如, 输入的字符串是否合理。
以下为代码片段
NumericTextBox
public class NumericTextBox : TextBox
{
bool allowSpace = false;
// Restricts the entry of characters to digits (including hex), the negative sign,
// the decimal point, and editing keystrokes (backspace).
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
if (Char.IsDigit(e.KeyChar))
{
// Digits are OK
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// Decimal separator is OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
// else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
// {
// // Let the edit control handle control and alt key combinations
// }
else if (this.allowSpace && e.KeyChar == ' ')
{
}
else
{
// Swallow this invalid key and beep
e.Handled = true;
// MessageBeep();
}
}
public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}
public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}
public bool AllowSpace
{
set
{
this.allowSpace = value;
}
get
{
return this.allowSpace;
}
}
}
{
bool allowSpace = false;
// Restricts the entry of characters to digits (including hex), the negative sign,
// the decimal point, and editing keystrokes (backspace).
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
if (Char.IsDigit(e.KeyChar))
{
// Digits are OK
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// Decimal separator is OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
// else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
// {
// // Let the edit control handle control and alt key combinations
// }
else if (this.allowSpace && e.KeyChar == ' ')
{
}
else
{
// Swallow this invalid key and beep
e.Handled = true;
// MessageBeep();
}
}
public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}
public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}
public bool AllowSpace
{
set
{
this.allowSpace = value;
}
get
{
return this.allowSpace;
}
}
}