samedi 24 octobre 2020

How to filter characters in C#

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

Aucun commentaire:

Enregistrer un commentaire