-2

I recently started working in C# as a hobby, I want to make a sort of a calculator. But I don't want to let my app crash when the user fills in a character that isn't a number. I already searched for topics like this but couldn't find what I needed :(

This is what I tried

I first made a char. These characters are the only characters my program may use

    char[] chars = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.' };

After this, I tried to make a kind of filter. But this works actually the opposite way.

        if (tb1.Text.IndexOfAny(chars) >= 0)
        {
            tb1.Text = "0";
        }

I also converted my string into a number like this.

double a = Convert.ToDouble(tb1.Text.Substring(0));

LvdB
  • 23
  • 5

2 Answers2

1

You are using an opposite way, you should find from array your value. For example:

    if (Array.IndexOf(chars, tb1.Text) >= 0)
    {
        tb1.Text = "0";
    }
shrzd
  • 102
  • 2
  • 3
  • 6
0

I Solved it like this

private void Button_Click_1(object sender, RoutedEventArgs e)
    {

        double a = Convert.ToDouble(tb1.Text.Substring(0));

    }

After this I created a function

private void tb1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tb1.Text == "")
            {
                return;
            }

            var input = CheckText(tb1.Text);

            tb1.Text = input;

            tb1.SelectionStart = input.Length;
            tb1.SelectionLength = 0;

        }

And check the input string

private string CheckText(string text, string pattern = "^(?!.*[^0-9.,\n]).*$")
    {

        var textCheck = Regex.IsMatch(text, pattern);
        if (!textCheck)
        {
            if (text.Length > 1)
            {
                text = text.Substring(0, text.Length - 1);
            }
            else
            {
                text = "";
            }
        }
        return text;
    }

Now you can't even fill in a number or another 'illegal' character

LvdB
  • 23
  • 5