我有一个windows窗体应用程序与一个文本框控件,我想只接受整数值。在过去,我通过重载KeyPress事件并删除不符合规范的字符来进行这种验证。我已经看了MaskedTextBox控件,但我想一个更通用的解决方案,可以与也许正则表达式,或依赖于其他控件的值。

理想情况下,按下非数字字符要么不产生结果,要么立即向用户提供关于无效字符的反馈。


当前回答

这里有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);
    }
}

其他回答

我也在寻找最好的方法来检查文本框中只有数字和键盘的问题是,它不支持通过右键单击或剪贴板复制粘贴,所以提出了这个代码,验证光标离开文本字段时,它也检查空字段。(newguy改编版)

private void txtFirstValue_MouseLeave(object sender, EventArgs e)
{
    int num;
    bool isNum = int.TryParse(txtFirstValue.Text.Trim(), out num);

    if (!isNum && txtFirstValue.Text != String.Empty)
    {
        MessageBox.Show("The First Value You Entered Is Not a Number, Please Try Again", "Invalid Value Detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
        txtFirstValue.Clear();
    }
}
Here is a simple solution that works for me.

public static bool numResult;
    public static bool checkTextisNumber(string numberVal)
    {
        try
        {
            if (numberVal.Equals("."))
            {
                numResult = true;
            }
            else if (numberVal.Equals(""))
            {
                numResult = true;
            }
            else
            {
                decimal number3 = 0;
                bool canConvert = decimal.TryParse(numberVal, out number3);
                if (canConvert == true)
                {
                    numResult = true;
                }
                else
                    numResult = false;
            }

        }
        catch (System.Exception ex)
        {
            numResult = false;
        }
        return numResult;
    }
    string correctNum;
    private void tBox_NumTester_TextChanged(object sender, TextChangedEventArgs e)
    {


        if(checkTextisNumber(tBox_NumTester.Text))
        {
            correctNum = tBox_NumTester.Text;
        }
        else
        {
            tBox_NumTester.Text = correctNum;
        }

    }

我从上下文和您使用的标记假设您正在编写一个。net c#应用程序。在这种情况下,您可以订阅文本更改事件,并验证每个按键。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
    {
        MessageBox.Show("Please enter only numbers.");
        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}

尝试一个MaskedTextBox。它采用一种简单的掩码格式,这样你就可以将输入限制为数字或日期之类的。

这是我的方法:

using linq (easy to modify filter) copy/paste proof code keeps caret position when you press a forbidden character accepts left zeroes and any size numbers private void numeroCuenta_TextChanged(object sender, EventArgs e) { string org = numeroCuenta.Text; string formated = string.Concat(org.Where(c => (c >= '0' && c <= '9'))); if (formated != org) { int s = numeroCuenta.SelectionStart; if (s > 0 && formated.Length > s && org[s - 1] != formated[s - 1]) s--; numeroCuenta.Text = formated; numeroCuenta.SelectionStart = s; } }