0

I have textbox1 where i enter number. Example: 123 I also have textbox2 where the sum is shown. Example: 6 (1+2+3)

What i need is. If there is only numbers in my textbox1, then everything is fine and i'm getting sum. If there is something more than numbers like 1a2b3c i want the programm to show message box with Warning and a text. Delete all non-digits? If the guy press Yes, then it does delete abc and only 123 is left. If no, then Error shows up.

My code:

 private void button1_Click(object sender, EventArgs e)
    {

        int cipari = Convert.ToInt32(textBox1.Text);

        int summa = 0;
        for (int n = cipari; n > 0; summa += n % 10, n /= 10) ;

        DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            textBox2.Text = summa.ToString();
        }
        else if (dialogResult == DialogResult.No)
        {
            textBox2.Text = "Error! You can't sum non-digits!";
        }


    }
Roberts Šensters
  • 585
  • 1
  • 7
  • 23
  • 5
    [Why not just make the textbox numbers only with a simple check?](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – Prix Sep 30 '15 at 18:11
  • 2
    `Convert.ToInt()` will crash if they entered a non-digit, so the rest of your code will never even take place. Use `Int.TryParse(string s, out int result)`. If it returns false, then you know they have entered invalid data. Then just loop over the string, find any non-digit (`!Char.IsDigit()`) and remove it, if so. – sab669 Sep 30 '15 at 18:19
  • Can you write your answer? I didn't really understand much cause i never really used Int.TryParse :( – Roberts Šensters Sep 30 '15 at 18:23

4 Answers4

1

Simply check for the prescence of non-digit characters:

foreach(Char c in textBox1.Text) {
    if( !Char.IsDigit( c ) ) {
        MessageBox.Show("Non-digits detected");
        return;
    }
}
Dai
  • 141,631
  • 28
  • 261
  • 374
0

That's an odd program flow honestly. But you can do it like:

if(!textBox2.Text.All(char.IsDigit)
{
    DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
        textBox2.Text = string.Concat(textBox2.Text.Where(char.IsDigit));
    }
    else if (dialogResult == DialogResult.No)
    {
        textBox2.Text = "Error! You can't sum non-digits!";
    }

}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

if you only want numbers then you can use a small function the scrub and warn the user on the textchanged event of each effected text box. This will show a warning to the user and then remove the invalid character.

private void validateText(TextBox tb)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(tb.Text, @"[^0-9]"))
            {
                MessageBox.Show("Please enter only numbers.");
                tb.Text = tb.Text.Remove(tb.Text.Length - 1);
                tb.Refresh();
                tb.SelectionStart = tb.Text.Length;
                tb.SelectionLength = 0;
            }
        }

use:

private void textbox1_TextChanged(object sender, EventArgs e)
        {
            validateText(textbox1);
        }
trapspring
  • 56
  • 7
-1

Why to delete numbers every time user enters alphabets, I guess the best practice is to never let the user enter anything else than a number.

First create a function that checks if the text entered is integer or not like this :

private bool IsNumber(string text)
    {
        Regex regex = new Regex("[^0-9.-]+"); //regex that matches if the text contains only numbers
        return regex.IsMatch(text);
    }

Then Use the textbox's PreviewTextInput event to stop the user from entering nothing but integers (decimal and -) too.

private void Button_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = IsNumber(e.Text);
    }

It's important to set the e.handled to the IsNumber function as here only it checks using this method if the input string is acceptable or not and prevents the user from entering it.

Manish Singh
  • 360
  • 1
  • 6
  • 18