Solved

C# code to handle non Numbers

Posted on 2011-03-14
11
367 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:bsharath
  • 3
  • 3
  • 2
  • +3
11 Comments
 
LVL 3

Expert Comment

by:ccwill88
ID: 35135006
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
 
LVL 11

Author Comment

by:bsharath
ID: 35135022
Sorry does not work
0
 
LVL 6

Expert Comment

by:nandithaa
ID: 35135316
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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 6

Expert Comment

by:nandithaa
ID: 35135327
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
 
LVL 11

Author Comment

by:bsharath
ID: 35135528
Thanks

Can you please explain what each of this does.

try
            {
               
             }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid input");
                button3_Click(sender, e);
            }
0
 
LVL 9

Expert Comment

by:Roman Gherman
ID: 35135568
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
 
LVL 9

Expert Comment

by:Roman Gherman
ID: 35135572
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
 
LVL 26

Expert Comment

by:EDDYKT
ID: 35136979
use tryparse
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35138658
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
 
LVL 6

Expert Comment

by:nandithaa
ID: 35155263
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
 
LVL 9

Accepted Solution

by:
Roman Gherman earned 500 total points
ID: 35155534
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question