繁体   English   中英

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

[英]How to only allow Integers into a textbox

我有一个凭证应用程序,当有人要创建活动凭证时,他们必须指定的字段之一是“目标受众”。 有时,该人员可能输入字符串或不是int的变量,并且服务器将崩溃。 我只想实现一个if语句,以查看其是否不是int,然后执行某些操作。 我有一个正则表达式,我只是不知道如何实现它。 尝试了很多事情。 (要验证的文本框是“ campaignAudience”)

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

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

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;
    }

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

使用:

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

PS也已使用此扩展方法进行了Unit testing

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

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);
    }
}

Linq版本:

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

正则表达式版本:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM