daengl daengl - 17 days ago 10
C# Question

Using UWP TextBox.TextChanging to ignore wrong data

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?

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;
    }
}