1

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

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

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

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

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

提前致谢!

4

6 回答 6

9

确保文本框是数字的更好方法是处理 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;
} 
于 2011-12-24T21:46:44.480 回答
4

做这件事有很多种方法:

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

  2. 您可以Regex用来验证:

    Match match = Regex.Match(textBox.Text, @"^\d+$");
    if (match.Success) { ... }
    // or
    if (Regex.IsMatch(textBox.Text, @"^\d+$")) { ... }
    
于 2011-12-24T21:16:57.763 回答
2

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

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

于 2011-12-24T21:34:34.203 回答
1

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

例子:

<TextBox InputScope="Digits"></TextBox>
于 2013-05-08T12:55:30.340 回答
0

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

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

Int64 output;
if (!Int64.TryParse(input, out output)
{
    ShowErrorMessage();
    return
}
Continue..
于 2011-12-24T21:13:06.963 回答
0
/// <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
}
于 2012-11-24T01:45:56.843 回答