开发者

Number only TextBox (WPF) [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do I get a TextBox to only accept numeric input in WPF?

The following codes are not correct :

 private  void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !AreAllValidNumericChars(e.Text);



    }
    private bool AreAllValidNumericChars(string str)
    {
        foreach (char c in str)
        {
            if (!Char.IsNumber(c)) return false;
        }

        return true;
    }

and

 private  void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !AreAllValidNumericChars(e.Text);

    }
    bool AreAllValidNumericChars(string str)
    {
        bool ret = true;
        if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol |
            str == System.Globalization.NumberFormatInfo.CurrentI开发者_StackOverflow社区nfo.PerMilleSymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
            return ret;

        int l = str.Length;
        for (int i = 0; i < l; i++)
        {
            char ch = str[i];
            ret &= Char.IsDigit(ch);
        }

        return ret;
    }

and

     private override void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        char c = e.Text.ToCharArray().First();
        e.Handled = !(char.IsNumber(c) || char.IsControl(c));

    }

and .....

The problem : Ctrl+V Copy/Paste

What is the correct code?


This is the code I used for number only textbox and is working fine.

private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = onlyNumeric(e.Text);
}

public static bool onlyNumeric(string text)
{
    Regex regex = new Regex("^[0-9]*$"); //regex that allows numeric input only
    return !regex.IsMatch(text); // 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜