如何只允许整数进入文本框

时间:2022-01-24 17:33:41

I have a voucher application, and when someone wants to create a campaign voucher, one of the fields they have to specify is "Target Audience". Sometimes the person might enter a string, or a variable that is not an int, and the server will just crash. I just want to implement an if statement to see if its NOT a int, and then do something. I have a regular expression, i just dont know how to implement it. Tried many things. (the textbox to validate is 'campaignAudience')

我有一个优惠券应用程序,当有人想创建一个活动优惠券时,他们必须指定的领域之一是“目标受众”。有时,这个人可能输入一个字符串,或者一个不是int的变量,服务器就会崩溃。我只想实现if语句,看看它是不是int型的,然后做点什么。我有一个正则表达式,只是不知道如何实现它。尝试了许多东西。(验证的文本框是“竞选听众”)

System.Text.RegularExpressions.Regex.IsMatch(campaignAudience.Value, "[ ^ 0-9]");

4 个解决方案

#1


2  

I have recently needed a similiar solution. Assuming you need an integer (number without decimal point).

我最近需要一个类似的解决方案。假设您需要一个整数(没有小数点的数)。

public static bool IntegerAndIsANumber(this string val)
    {
        if (string.IsNullOrEmpty(val) || val.Contains(',') || val.Contains('.'))
            return false;

        decimal decimalValue;
        if (!Decimal.TryParse(val, out decimalValue))
            return false;

        decimal fraction = decimalValue - (Int64)decimalValue;
        if (fraction == 0)
            return true;

        return false;
    }

It checks if given string is an Integer and if it is a number in the first place.

它首先检查给定的字符串是否是整数,以及它是否是数字。

Using:

使用:

if(YourString.IntegerAndIsANumber()){
  //value is Integer
  }
  else{
  //incorrect value 
  }

P.S. Also have done Unit testing with this extension method.

P.S.也用这种扩展方法做了单元测试。

#2


1  

Use a custom TextBox that only accepts numbers, add the following to your project, compile then the custom TextBox will appear at the top of the toolbox when your form is shown in the IDE. Add the TextBox to the form and now the user can only enter digits.

使用一个只接受数字的自定义文本框,将以下内容添加到项目中,然后编译,当表单显示在IDE中时,自定义文本框将出现在工具箱的顶部。将文本框添加到表单中,现在用户只能输入数字。

using System;

using System.Windows.Forms;

public class numericTextbox : TextBox
{
    private const int WM_PASTE = 0x302;

    protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
    {
        string Value = this.Text;
        Value = Value.Remove(this.SelectionStart, this.SelectionLength);
        Value = Value.Insert(this.SelectionStart, e.KeyChar.ToString());
        e.Handled = Convert.ToBoolean(Value.LastIndexOf("-") > 0) || 
            !(char.IsControl(e.KeyChar) || 
              char.IsDigit(e.KeyChar) || 
            (e.KeyChar == '.' && !(this.Text.Contains(".")) || 
             e.KeyChar == '.' && this.SelectedText.Contains(".")) || 
            (e.KeyChar == '-' && this.SelectionStart == 0));

        base.OnKeyPress(e);

    }
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_PASTE)
        {
            string Value = this.Text;
            Value = Value.Remove(this.SelectionStart, this.SelectionLength);
            Value = Value.Insert(this.SelectionStart, Clipboard.GetText());
            decimal result = 0M;
            if (!(decimal.TryParse(Value, out result)))
            {
                return;
            }
        }
        base.WndProc(ref m);
    }
}

#3


0  

Linq version:

if(campaignAudience.Value.All(x => Char.IsLetter(x)))
{
    // text input is OK
}

Regex version:

if(new Regex("^[A-Za-z]*$").Match(campaignAudience.Value).Success)
{
    // text input is OK
}

#4


0  

Limit the keypress event of the textbox to digits

将文本框的按键事件限制为数字。

#1


2  

I have recently needed a similiar solution. Assuming you need an integer (number without decimal point).

我最近需要一个类似的解决方案。假设您需要一个整数(没有小数点的数)。

public static bool IntegerAndIsANumber(this string val)
    {
        if (string.IsNullOrEmpty(val) || val.Contains(',') || val.Contains('.'))
            return false;

        decimal decimalValue;
        if (!Decimal.TryParse(val, out decimalValue))
            return false;

        decimal fraction = decimalValue - (Int64)decimalValue;
        if (fraction == 0)
            return true;

        return false;
    }

It checks if given string is an Integer and if it is a number in the first place.

它首先检查给定的字符串是否是整数,以及它是否是数字。

Using:

使用:

if(YourString.IntegerAndIsANumber()){
  //value is Integer
  }
  else{
  //incorrect value 
  }

P.S. Also have done Unit testing with this extension method.

P.S.也用这种扩展方法做了单元测试。

#2


1  

Use a custom TextBox that only accepts numbers, add the following to your project, compile then the custom TextBox will appear at the top of the toolbox when your form is shown in the IDE. Add the TextBox to the form and now the user can only enter digits.

使用一个只接受数字的自定义文本框,将以下内容添加到项目中,然后编译,当表单显示在IDE中时,自定义文本框将出现在工具箱的顶部。将文本框添加到表单中,现在用户只能输入数字。

using System;

using System.Windows.Forms;

public class numericTextbox : TextBox
{
    private const int WM_PASTE = 0x302;

    protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
    {
        string Value = this.Text;
        Value = Value.Remove(this.SelectionStart, this.SelectionLength);
        Value = Value.Insert(this.SelectionStart, e.KeyChar.ToString());
        e.Handled = Convert.ToBoolean(Value.LastIndexOf("-") > 0) || 
            !(char.IsControl(e.KeyChar) || 
              char.IsDigit(e.KeyChar) || 
            (e.KeyChar == '.' && !(this.Text.Contains(".")) || 
             e.KeyChar == '.' && this.SelectedText.Contains(".")) || 
            (e.KeyChar == '-' && this.SelectionStart == 0));

        base.OnKeyPress(e);

    }
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_PASTE)
        {
            string Value = this.Text;
            Value = Value.Remove(this.SelectionStart, this.SelectionLength);
            Value = Value.Insert(this.SelectionStart, Clipboard.GetText());
            decimal result = 0M;
            if (!(decimal.TryParse(Value, out result)))
            {
                return;
            }
        }
        base.WndProc(ref m);
    }
}

#3


0  

Linq version:

if(campaignAudience.Value.All(x => Char.IsLetter(x)))
{
    // text input is OK
}

Regex version:

if(new Regex("^[A-Za-z]*$").Match(campaignAudience.Value).Success)
{
    // text input is OK
}

#4


0  

Limit the keypress event of the textbox to digits

将文本框的按键事件限制为数字。