Solved

C# code to handle non Numbers

Posted on 2011-03-14
11
356 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
Comment Utility
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
Comment Utility
Sorry does not work
0
 
LVL 6

Expert Comment

by:nandithaa
Comment Utility
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
 
LVL 6

Expert Comment

by:nandithaa
Comment Utility
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
Comment Utility
Thanks

Can you please explain what each of this does.

try
            {
               
             }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid input");
                button3_Click(sender, e);
            }
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 9

Expert Comment

by:Roman Gherman
Comment Utility
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
Comment Utility
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
Comment Utility
use tryparse
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
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
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
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.

763 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now