我有一个windows窗体应用程序与一个文本框控件,我想只接受整数值。在过去,我通过重载KeyPress事件并删除不符合规范的字符来进行这种验证。我已经看了MaskedTextBox控件,但我想一个更通用的解决方案,可以与也许正则表达式,或依赖于其他控件的值。
理想情况下,按下非数字字符要么不产生结果,要么立即向用户提供关于无效字符的反馈。
我有一个windows窗体应用程序与一个文本框控件,我想只接受整数值。在过去,我通过重载KeyPress事件并删除不符合规范的字符来进行这种验证。我已经看了MaskedTextBox控件,但我想一个更通用的解决方案,可以与也许正则表达式,或依赖于其他控件的值。
理想情况下,按下非数字字符要么不产生结果,要么立即向用户提供关于无效字符的反馈。
当前回答
我已经为各种验证创建了一个可重用的文本框扩展类,并考虑共享它。
您所需要做的就是引发一个TextChange事件,然后调用Validate方法。它是这样的:
private void tbxAmount_TextChanged(object sender, EventArgs e)
{
tbxAmount.Validate(TextValidator.ValidationType.Amount);
}
下面是扩展类:
public static class TextValidator
{
public enum ValidationType
{
Amount,
Integer
}
/// <summary>
/// Validate a textbox on text change.
/// </summary>
/// <param name="tbx"></param>
/// <param name="validationType"></param>
public static void Validate(this TextBox tbx, ValidationType validationType)
{
PerformValidation(tbx, validationType);
tbx.Select(tbx.Text.Length, 0);
}
private static void PerformValidation(this TextBox tbx, ValidationType validationType)
{
char[] enteredString = tbx.Text.ToCharArray();
switch (validationType)
{
case ValidationType.Amount:
tbx.Text = AmountValidation(enteredString);
break;
case ValidationType.Integer:
tbx.Text = IntegerValidation(enteredString);
break;
default:
break;
}
tbx.SelectionStart = tbx.Text.Length;
}
private static string AmountValidation(char[] enteredString)
{
string actualString = string.Empty;
int count = 0;
foreach (char c in enteredString.AsEnumerable())
{
if (count >= 1 && c == '.')
{ actualString.Replace(c, ' '); actualString.Trim(); }
else
{
if (Char.IsDigit(c))
{
actualString = actualString + c;
}
if (c == '.')
{
actualString = actualString + c; count++;
}
else
{
actualString.Replace(c, ' ');
actualString.Trim();
}
}
}
return actualString;
}
private static string IntegerValidation(char[] enteredString)
{
string actualString = string.Empty;
foreach (char c in enteredString.AsEnumerable())
{
if (Char.IsDigit(c))
{
actualString = actualString + c;
}
else
{
actualString.Replace(c, ' ');
actualString.Trim();
}
}
return actualString;
}
}
你可以在这里找到完整的代码
其他回答
只需使用NumericUpDown控件,并设置那些丑陋的上下按钮可见性为假。
numericUpDown1.Controls[0].Visible = false;
NumericUpDown实际上是一个包含“旋转框”(上下按钮)的控件集合,一个文本框和一些代码来验证和wange-jangle。
标记:
YourNumericUpDown.Controls[0].visible = false
将隐藏按钮,同时保持底层代码活动。
虽然不是一个明显的解决方案,但它简单而有效。. controls[1]将隐藏文本框部分,如果你想这样做的话。
只是因为在一条线上做事情总是更有趣……
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
注意:这并不阻止用户复制/粘贴到此文本框。这并不是清除数据的安全方法。
尝试一个MaskedTextBox。它采用一种简单的掩码格式,这样你就可以将输入限制为数字或日期之类的。
int Number;
bool isNumber;
isNumber = int32.TryPase(textbox1.text, out Number);
if (!isNumber)
{
(code if not an integer);
}
else
{
(code if an integer);
}
这里有30多个答案,很多答案都是有用的。但我想分享system。windows。forms。textbox和system。windows。controls。textbox的通用形式。
在System.Windows.Controls.TextBox中没有可用的按键事件。 这个答案是为那些想用同样的逻辑实现System.Windows.Forms.TextBox和System.Windows.Controls.TextBox的人准备的。
这是NumberTextBox代码。对于System.Windows.Controls.TextBox,使用注释行代替之前的行。
public class NumberTextBox : System.Windows.Forms.TextBox
//public class NumberTextBox : System.Windows.Controls.TextBox
{
private double _maxValue;
private double _minValue;
private bool _flag;
private string _previousValue;
public NumberTextBox()
{
this.TextAlign = HorizontalAlignment.Right;
//TextAlignment = TextAlignment.Right;
KeyDown += TextBox_KeyDown;
TextChanged += TextBox_TextChanged;
_minValue = double.MinValue;
_maxValue = double.MaxValue;
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
_previousValue = this.Text;
_flag = this.SelectedText.Length > 0;
}
private void TextBox_TextChanged(object sender, EventArgs e)
//private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var text = this.Text;
if (text.Length < 1) return;
var cursorPosition = SelectionStart == 0 ? SelectionStart : SelectionStart - 1;
var insertedChar = text[cursorPosition];
if (IsInvalidInput(insertedChar, cursorPosition, text))
{
HandleText(text, cursorPosition);
}
ValidateRange(text, cursorPosition);
}
private bool IsInvalidInput(char insertedChar, int cursorPosition, string text)
{
return !char.IsDigit(insertedChar) && insertedChar != '.' && insertedChar != '-' ||
insertedChar == '-' && cursorPosition != 0 ||
text.Count(x => x == '.') > 1 ||
text.Count(x => x == '-') > 1;
}
private void HandleText(string text, int cursorPosition)
{
this.Text = _flag ? _previousValue : text.Remove(cursorPosition, 1);
this.SelectionStart = cursorPosition;
this.SelectionLength = 0;
}
private void ValidateRange(string text, int cursorPosition)
{
try
{
if (text == "." || _minValue < 0 && text == "-") return;
var doubleValue = Convert.ToDouble(text);
if (doubleValue > _maxValue || doubleValue < _minValue)
{
HandleText(text, cursorPosition);
}
}
catch (Exception)
{
HandleText(text, cursorPosition);
}
}
protected void SetProperties(double minValue = double.MinValue, double maxValue = double.MaxValue)
{
_minValue = minValue;
_maxValue = maxValue;
}
}
PositiveNumberTextBox代码:
public class PositiveNumberTextBox : NumberTextBox
{
public PositiveNumberTextBox()
{
SetProperties(0);
}
}
FractionNumberTextBox代码:
public class FractionNumberTextBox : NumberTextBox
{
public FractionNumberTextBox()
{
SetProperties(0, 0.999999);
}
}