C# 仅数字文本框

C# 仅数字文本框,c#,windows-phone-7,numerical-analysis,C#,Windows Phone 7,Numerical Analysis,我已经到处找过了,但我看到的例子似乎只允许数字0-9 我在写一个毕达哥拉斯定理程序。我希望让手机(Windows phone 7)检查文本框中是否有任何字母(A-Z,A-Z)、符号(@、%)或除数字以外的任何内容。如果没有,那么它将继续计算。我想检查一下,这样以后就不会有错误了 这基本上是一个糟糕的伪代码,我希望它做什么 txtOne-->任何alpha?--无-->任何符号--无-->继续 实际上,我更喜欢使用命令来检查字符串是否完全是一个数字 提前谢谢 您可以使用TryParse并查看是否有

我已经到处找过了,但我看到的例子似乎只允许数字0-9

我在写一个毕达哥拉斯定理程序。我希望让手机(Windows phone 7)检查文本框中是否有任何字母(A-Z,A-Z)、符号(@、%)或除数字以外的任何内容。如果没有,那么它将继续计算。我想检查一下,这样以后就不会有错误了

这基本上是一个糟糕的伪代码,我希望它做什么

txtOne-->任何alpha?--无-->任何符号--无-->继续

实际上,我更喜欢使用命令来检查字符串是否完全是一个数字


提前谢谢

您可以使用TryParse并查看是否有结果


您可以使用TryParse并查看是否有结果


有几种方法可以做到这一点:

  • 您可以使用
    TryParse()
    并检查返回值是否为false

  • 您可以使用
    Regex
    验证:

    Match match = Regex.Match(textBox.Text, @"^\d+$");
    if (match.Success) { ... }
    // or
    if (Regex.IsMatch(textBox.Text, @"^\d+$")) { ... }
    

  • 有几种方法可以做到这一点:

  • 您可以使用
    TryParse()
    并检查返回值是否为false

  • 您可以使用
    Regex
    验证:

    Match match = Regex.Match(textBox.Text, @"^\d+$");
    if (match.Success) { ... }
    // or
    if (Regex.IsMatch(textBox.Text, @"^\d+$")) { ... }
    

  • 或者你可以只给他们数字键盘。您可以使用几种不同的键盘布局


    如果你想做更深入的工作,我已经使用KeyDown和KeyUp事件来检查输入的内容并处理按键

    或者你只需给他们数字键盘。您可以使用几种不同的键盘布局


    如果你想做更深入的工作,我已经使用KeyDown和KeyUp事件来检查输入的内容并处理按键

    确保文本框是数字的更好方法是处理按键事件。然后可以选择要允许的字符。在以下示例中,我们不允许所有非数字字符:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // If the character is not a digit, don't let it show up in the textbox.
        if (!char.IsDigit(e.KeyChar))
            e.Handled = true;
    }
    
    这可以确保文本框文本是数字,因为它只允许输入数字


    这是我刚刚提出的允许十进制值(显然还有退格键)的方法:


    确保文本框是数字的更好方法是处理按键事件。然后可以选择要允许的字符。在以下示例中,我们不允许所有非数字字符:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // If the character is not a digit, don't let it show up in the textbox.
        if (!char.IsDigit(e.KeyChar))
            e.Handled = true;
    }
    
    这可以确保文本框文本是数字,因为它只允许输入数字


    这是我刚刚提出的允许十进制值(显然还有退格键)的方法:

    //
    ///仅限数字的文本框。
    /// 
    公共类NumericOnlyTextBox:TextBox
    {
    #区域属性
    #区域异倍体
    /// 
    ///获取或设置一个值,该值指示[是否允许小数]。
    /// 
    /// 
    ///如果[允许小数],则为true;否则为false。
    /// 
    公共场所许可证
    {
    get{return(bool)GetValue(AllowDecimalsProperty);}
    set{SetValue(AllowDecimalsProperty,value);}
    }
    /// 
    ///allow decimals属性
    /// 
    公共静态只读从属属性AllowDecimalsProperty=
    从属属性寄存器(“AllowDecimals”,类型(bool),
    typeof(NumericOnlyTextBox),新UIPropertyMetadata(false));
    #端区
    #区域最大值
    /// 
    ///获取或设置最大值。
    /// 
    /// 
    ///最大值。
    /// 
    公共双?最大值
    {
    获取{return(double?)GetValue(MaxValueProperty);}
    set{SetValue(MaxValueProperty,value);}
    }
    /// 
    ///最大值属性
    /// 
    公共静态只读从属属性MaxValueProperty=
    DependencyProperty.Register(“MaxValue”),typeof(double?),
    typeof(NumericOnlyTextBox),新的UIPropertyMetadata(null);
    #端区
    #区域最小值
    /// 
    ///获取或设置最小值。
    /// 
    /// 
    ///最小值。
    /// 
    公共双极小值
    {
    获取{return(double?)GetValue(MinValueProperty);}
    set{SetValue(MinValueProperty,value);}
    }
    /// 
    ///最小值属性
    /// 
    公共静态只读从属属性MinValueProperty=
    DependencyProperty.Register(“MinValue”),typeof(double?),
    typeof(NumericOnlyTextBox),新的UIPropertyMetadata(null);
    #端区
    #端区
    #区域构造函数
    /// 
    ///初始化类的新实例。
    /// 
    public NumericOnlyTextBox()
    {
    this.previewtextireput+=onpreviewtextireput;
    }
    #端区
    #区域方法
    /// 
    ///仅数字文本字段。
    /// 
    ///文本。
    /// 
    公共bool NumericOnlyCheck(字符串文本)
    {
    //匹配不允许的文本的正则表达式
    var正则表达式=(AllowDecimals)?新正则表达式([^0-9.]+”):新正则表达式([^0-9]+”);
    return!regex.IsMatch(text);
    }
    #端区
    #地区活动
    /// 
    ///在[预览文本输入]时调用。
    /// 
    ///发送者。
    ///实例
    ///包含事件数据。
    /// 
    private void onPreviewTestInput(对象发送者,文本复合目标)
    {
    //支票号码
    if(this.NumericOnlyCheck(e.Text))
    {
    //求最小值
    if(MinValue!=null&&Convert.ToDouble(this.Text+e.Text)MaxValue)
    {
    this.Text=MaxValue.ToString();
    this.SelectionStart=this.Text.Length;
    e、 已处理=正确;
    }
    }
    其他的
    {
    e、 已处理=正确;
    }
    }
    #端区
    }
    
    //
    ///只有数字的tex
    
    /// <summary>
    /// A numeric-only textbox.
    /// </summary>
    public class NumericOnlyTextBox : TextBox
    {
        #region Properties
    
        #region AllowDecimals
    
        /// <summary>
        /// Gets or sets a value indicating whether [allow decimals].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [allow decimals]; otherwise, <c>false</c>.
        /// </value>
        public bool AllowDecimals
        {
            get { return (bool)GetValue(AllowDecimalsProperty); }
            set { SetValue(AllowDecimalsProperty, value); }
        }
    
        /// <summary>
        /// The allow decimals property
        /// </summary>
        public static readonly DependencyProperty AllowDecimalsProperty =
            DependencyProperty.Register("AllowDecimals", typeof(bool), 
            typeof(NumericOnlyTextBox), new UIPropertyMetadata(false));
    
        #endregion
    
        #region MaxValue
    
        /// <summary>
        /// Gets or sets the max value.
        /// </summary>
        /// <value>
        /// The max value.
        /// </value>
        public double? MaxValue
        {
            get { return (double?)GetValue(MaxValueProperty); }
            set { SetValue(MaxValueProperty, value); }
        }
    
        /// <summary>
        /// The max value property
        /// </summary>
        public static readonly DependencyProperty MaxValueProperty =
            DependencyProperty.Register("MaxValue", typeof(double?), 
            typeof(NumericOnlyTextBox), new UIPropertyMetadata(null));
    
        #endregion
    
        #region MinValue
    
        /// <summary>
        /// Gets or sets the min value.
        /// </summary>
        /// <value>
        /// The min value.
        /// </value>
        public double? MinValue
        {
            get { return (double?)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }
    
        /// <summary>
        /// The min value property
        /// </summary>
        public static readonly DependencyProperty MinValueProperty =
            DependencyProperty.Register("MinValue", typeof(double?), 
            typeof(NumericOnlyTextBox), new UIPropertyMetadata(null));
    
        #endregion
    
        #endregion
    
        #region Contructors
    
        /// <summary>
        /// Initializes a new instance of the <see cref="NumericOnlyTextBox" /> class.
        /// </summary>
        public NumericOnlyTextBox()
        {
            this.PreviewTextInput += OnPreviewTextInput;        
        }
    
        #endregion
    
        #region Methods
    
        /// <summary>
        /// Numeric-Only text field.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public bool NumericOnlyCheck(string text)
        {
            // regex that matches disallowed text
            var regex = (AllowDecimals) ? new Regex("[^0-9.]+") : new Regex("[^0-9]+");
            return !regex.IsMatch(text);
        }
    
        #endregion
    
        #region Events
    
        /// <summary>
        /// Called when [preview text input].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="TextCompositionEventArgs" /> instance 
        /// containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // Check number
            if (this.NumericOnlyCheck(e.Text))
            {
                // Evaluate min value
                if (MinValue != null && Convert.ToDouble(this.Text + e.Text) < MinValue)
                {
                    this.Text = MinValue.ToString();
                    this.SelectionStart = this.Text.Length;
                    e.Handled = true;
                }
    
                // Evaluate max value
                if (MaxValue != null && Convert.ToDouble(this.Text + e.Text) > MaxValue)
                {
                    this.Text = MaxValue.ToString();
                    this.SelectionStart = this.Text.Length;
                    e.Handled = true;
                }
            }
    
            else
            {
                e.Handled = true;
            }
        }
    
        #endregion
    }
    
    <TextBox InputScope="Digits"></TextBox>