Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm creating a UWP app which has different TextBoxes to enter numbers. To make sure only numbers can be entered I use the TextChanging event. Sadly I can't find any documentation on how to use TextChanging in detail to ignore wrong inputs.

A working solution for one TextBox is the following:

string oldText;
private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    double temp;
    if (double.TryParse(sender.Text, out temp) || sender.Text == "")
        oldText = sender.Text;
    else
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = oldText;
        sender.SelectionStart = pos;
    }
}

Using this solution I would need a string oldText for each TextBox and either also a TextChanging function for each of it or a lot more code inside the function.

Is there a easy way to ignore "wrong" inputs in the TextBox.TextChanging event?

See Question&Answers more detail:os

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

1 Answer

With the help of Romasz link in his first comment I came up with this solution:

private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    double dtemp;
    if (!double.TryParse(sender.Text, out dtemp) && sender.Text != "")
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = sender.Text.Remove(pos, 1);
        sender.SelectionStart = pos;
    }
}

This works quite fine except when a part of the input value is selected and then a wrong character is entered.

Edit: I improved the above version to use Regex. So now I'm able to check whatever content should be allowed to enter:

private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    if (!Regex.IsMatch(sender.Text, "^\d*\.?\d*$") && sender.Text != "")
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = sender.Text.Remove(pos, 1);
        sender.SelectionStart = pos;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...