【问题标题】:Numeric Only TextBox仅限数字的文本框
【发布时间】:2012-01-27 10:50:04
【问题描述】:

我到处查看,但似乎我看到的示例只允许数字 0-9

我正在编写一个勾股定理程序。我希望手机 (Windows Phone 7) 检查文本框中是否有 ANY alpha (A-Z, a-z)、符号 (@,%) 或除数字以外的任何内容。如果没有,那么它将继续计算。我想检查一下,这样以后就不会出错了。

这基本上是我想要它做的一个糟糕的伪代码

txtOne-->任何字母?--否-->任何符号--否-->继续...

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

提前致谢!

【问题讨论】:

  • 如何在您的 TextBox 数据上使用 TryParse 方法之一。 Int32.TryParseDecimal.TryParse 取决于您的数据类型。
  • 最好检查字符串中的所有字符是否都是数字,而不是检查它们是否是无数非数字之一。

标签: c# windows-phone-7 numerical-analysis


【解决方案1】:

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

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 (char.IsDigit(e.KeyChar))
    {
        return;
    }
    if (e.KeyChar == (char)Keys.Back)
    {
        return;
    }
    if (e.KeyChar == '.' && !textBox1.Text.Contains('.'))
    {
        return;
    }
    e.Handled = true;
} 

【讨论】:

  • 通常您也必须处理从剪贴板粘贴,但我不知道这是否是 Windows Phone 7 上的问题。
  • @arx 你做的,好点。您还需要处理 TextChanged。
【解决方案2】:

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

  1. 可以使用TryParse(),检查返回值是否不为假。

  2. 您可以使用Regex进行验证:

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

【讨论】:

    【解决方案3】:

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

    如果您想更深入地了解,我使用了 KeyDown 和 KeyUp 事件来检查输入的内容并处理按键操作。 Link

    【讨论】:

    • 设备也可能有物理键盘。
    【解决方案4】:

    您可以定义文本框的输入范围。

    例子:

    <TextBox InputScope="Digits"></TextBox>
    

    【讨论】:

      【解决方案5】:

      你可以使用 TryParse 看看有没有结果。

      http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

      Int64 output;
      if (!Int64.TryParse(input, out output)
      {
          ShowErrorMessage();
          return
      }
      Continue..
      

      【讨论】:

        【解决方案6】:
        /// <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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-09-12
          • 1970-01-01
          • 1970-01-01
          • 2018-06-17
          • 1970-01-01
          • 2016-05-22
          • 2012-07-11
          相关资源
          最近更新 更多