Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c# - How to make a textBox accept only Numbers and just one decimal point in Windows 8

I am new to windows 8 phone. I am writing a calculator app that can only accept numbers in the textbox and just a single decimal point. how do I prevent users from inputting two or more decimal Points in the text box as the calculator cant handle that.

I have been using Keydown Event, is that the best or should I use Key up?

private void textbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also use RegExp with TextChanged event: The snippet below will handle any integer and float number, both positive and negative

    string previousInput = "";
    private void InputTextbox_TextChanged(object sender, RoutedEventArgs e)
    {
        Regex r = new Regex("^-{0,1}d+.{0,1}d*$"); // This is the main part, can be altered to match any desired form or limitations
        Match m = r.Match(InputTextbox.Text);
        if (m.Success)
        {
            previousInput = InputTextbox.Text;
        }
        else
        {
            InputTextbox.Text = previousInput;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...