luigi
luigi

Reputation: 109

How to Delete char in textbox that IS NOT a number?

I need to use text changing because I also need to allow input via speech and ink handwriting

private void Year_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
        {
            //after text changing check every character to see if it's an int.

            for (int i = 0; i < sender.Text.Length; i++)
            {
                if(Char.IsNumber(sender.Text[i]))
                {
                    return;
                }

                else if (!Char.IsNumber(sender.Text[i]))
                {
                    sender.Text.Remove(i);
                }
            }
        }

Upvotes: 0

Views: 46

Answers (2)

Xie Steven
Xie Steven

Reputation: 8621

Why not use the TextBox extension of the UWP - Windows Community Toolkit? It has helped you do all judgements.

You just need to install the nuget package Microsoft.Toolkit.Uwp.UI for your UWP project and then use it on XAML page like the following:

xmlns:extensions="using:Microsoft.Toolkit.Uwp.UI.Extensions"
<TextBox extensions:TextBoxRegex.ValidationType="Number" extensions:TextBoxRegex.ValidationMode="Dynamic"></TextBox>

Upvotes: 1

akhil kumar
akhil kumar

Reputation: 11

Firstly, Lets get to the question how to find whether a char is number or not? In this case what I generally prefer is to change the given char to number.If it is a number the answer lies between 0 to 9. So, the question now is how do you convert? The simplest way is to subtract with char '0'. Therefore by subtracting we get the difference which is the original number. for Example, The ASCII value of char '0' is 48 The ASCII value of char '5' is 53 as the difference between characters gives us difference between their ASCII values we get the number.

So, now get the char from the textbox and subtract each char with char '0' if it's value doesn't lie between 0 and 9 you can remove.

Upvotes: 1

Related Questions