[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# code to handle non Numbers

Posted on 2011-03-14
11
Medium Priority
?
387 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 86

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 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
Suggested Courses
Course of the Month19 days, 7 hours left to enroll

872 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