C# code to handle non Numbers

Hi,

C# code to handle non Numbers

The below code is a simple calc.

1. I dont want any error on any special characters or alphabets used. It has to say its invalid or something like that but not through an error

Regards
Sharath
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        int a, b, c;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            a = int.Parse(textBox1.Text);
            b = int.Parse(textBox2.Text);
            c = a + b;

            label4.Text = c.ToString();
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

            a = int.Parse(textBox1.Text);
            b = int.Parse(textBox2.Text);
            c = a - b;

            label5.Text = c.ToString();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            label4.Text = "";
            label5.Text = "";
            textBox1.Focus();
          
        }
    }
}

Open in new window

LVL 11
bsharathAsked:
Who is Participating?
 
Roman GhermanConnect With a Mentor Senior Software EngineerCommented:
Hi,

I think the simplest solution and the most correct one is with int.TryParse.

try - catch was not implemented to make conditional statements but to catch exceptions.

With int.TryParse you can check if string can be parsed to int or not and it returns a bool value:
true if success, false if failed to parse.

if(int.TryParse(textBox1.Text, out a) && int.TryParse(extBox2.Text, out b)
{
   c = a + b;
   label4.Text = c.ToString();
}

Open in new window


-----------------------
You can find me on: http://extremedev.blogspot.com
0
 
ccwill88Commented:
use try ..cache to handle the error
try
{
           a = int.Parse(textBox1.Text);
            b = int.Parse(textBox2.Text);
            c = a + b;

            label4.Text = c.ToString();
}
cache(ex)
{
}

Open in new window

0
 
bsharathAuthor Commented:
Sorry does not work
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
nandithaaCommented:
Try this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        int a, b, c;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
           
           try
            {
                a = int.Parse(textBox1.Text);
                b = int.Parse(textBox2.Text);
                c = a + b;

                label4.Text = c.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid input");
                button3_Click(sender, e);
            }
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
           try
            {
            a = int.Parse(textBox1.Text);
            b = int.Parse(textBox2.Text);
            c = a - b;

            label5.Text = c.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid input");
                button3_Click(sender, e);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            label4.Text = "";
            label5.Text = "";
            textBox1.Focus();
          
        }
    }
}

Open in new window

0
 
nandithaaCommented:
Or else, you can prevent users from entering non integer values by writing following Code in KeyPress event of textbox. So that users won't be able to type any other characters in textbox other than numbers.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

Open in new window

0
 
bsharathAuthor Commented:
Thanks

Can you please explain what each of this does.

try
            {
               
             }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid input");
                button3_Click(sender, e);
            }
0
 
Roman GhermanSenior Software EngineerCommented:
Hi,
Why not simply use int.TryParse ?

You could use it like this:

a = int.Parse(textBox1.Text);
b = int.Parse(textBox2.Text);
c = a + b;
if(int.TryParse(textBox1.Text, out a) && int.TryParse(extBox2.Text, out b)
{
   c = a + b;
   label4.Text = c.ToString();
}

Open in new window


-----------------------
You can find me on: http://extremedev.blogspot.com
0
 
Roman GhermanSenior Software EngineerCommented:
oops, sorry, delete:
a = int.Parse(textBox1.Text);
b = int.Parse(textBox2.Text);
c = a + b;

I was using it as referrence.

-----------------------
You can find me on: http://extremedev.blogspot.com
0
 
EDDYKTCommented:
use tryparse
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
I'd use TryParse() as suggested by roma1123 and EDDYKT.

*I wrote this last night but EE was down for maintenance when I tried to post:
private void button1_Click(object sender, EventArgs e)
        {
            int intA;
            if (int.TryParse(textBox1.Text, out intA))
            {
                int intB;
                if (int.TryParse(textBox2.Text, out intB))
                {
                    int intC = intA + intB;
                    label4.Text = intC.ToString();
                }
                else
                {
                    MessageBox.Show("Please enter a valid Integer.", "Invalid Integer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    textBox2.Focus();
                    textBox2.SelectAll();
                }
            }
            else
            {
                MessageBox.Show("Please enter a valid Integer.", "Invalid Integer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBox1.Focus();
                textBox1.SelectAll();
            }
        }

Open in new window

0
 
nandithaaCommented:
try-catch is used to handle exceptions. So when an exception is thrown it looks catch statement to handle the exception. So write code on how to handle exception in Catch block.

So in my example, when u enter any alphabet or any other non integer values,  compiler throws an exception when trying to parse it to integer, so the catch statement catch that exception and to handle it it execute the code written in catch block. That is a message box will be shown saying "Invalid input" and click event of button3 is fired to clear all fields.

Hope i cleared your doubt....
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.