C#: Exception handling(?)

dashing.sujay

Moving
Staff member
I have recently started learning C#. I was making a simple form application to calculate sum of fruits (checked through checkboxes) and quantity entered.

Problem is coming in quantity.

Code:
[B]if (Convert.ToInt32(textBox1.Text) > 0)[/B]
            {
                if (checkBox1.Checked)
                {
                    qua1 = Convert.ToInt32(textBox1.Text);
                }
                else
                {
                    MessageBox.Show("Please Check the respective items before entering values.");
                }
            }
            else
            {
                MessageBox.Show("Value of Quantity should be positive");
                qua1 = 0;
                textBox1.Text = "0";
            }

Exception is occuring in bold line when I'm running the program without entering any value textBox1 (quantity). Default value is 0. One thing is understood that exception is occuring due to the fact the compiler is in dilemma when it has to convert a blank value (" ") to an int which is rendering an exception. How to handle it?

Another query. I have restricted entry of values in textBoxes to numerics only by using this-

Code:
private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).

TIY :)
 

RBX

In the zone
why not change if (Convert.ToInt32(textBox1.Text) > 0)
to if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0)
 
Change this
Code:
private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

to something

Code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool isValidKey = char.IsDigit(e.KeyChar) || 
                                       e.KeyChar == '\b';
            e.Handled = !isValidKey;
        }

if e.Handled is TRUE then the key press is muted
see ref. KeyPressEventArgs.Handled Property (System.Windows.Forms)
 

nbaztec

Master KOD3R
Exception is occuring in bold line when I'm running the program without entering any value textBox1 (quantity). Default value is 0. One thing is understood that exception is occuring due to the fact the compiler is in dilemma when it has to convert a blank value (" ") to an int which is rendering an exception. How to handle it?
You are doing things wrong and/or you got the basics wrong.

Convert.ToInt32() expects a number as a string (in the current overloaded form), An empty string is NOT a number, it's NOT null, it's just a string with length 0, i.e. an empty string. On the other hand "0", "1234", "65535" are numeric strings.
You might be confused since in C++, NULL was an int(0).

You should instead be handling the FormatException:
Code:
     int value = 0;
     try{
          value = Convert.ToInt32(value);
     } catch(FormatException){
           MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

But looking closely you don't need Convert.ToInt32() since it's primarily used for much complex conversions from bytes, you can do away with just :
Code:
     int.Parse(value);

or better, simply use:
Code:
     int intVal;
     if(int.TryParse(value, out intVal)){
          // intVal is initialized to either the value or 0
     } else{
          MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }


Code:
private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).

TIY :)
I remember doing a similar thing eons ago. What I learnt was it wasn't worth it using this validation approach. Using this way, you effectively block out numerous valid keys out of the textbox which are not numeric, eg: Backspace, Del, Home, Ctrl/Shift, +/-, etc.
The proper way is to just validate on form submit, or if you are hell bent upon a KeyEvent validation, might I suggest doing it like this (the way I did it long ago):

Code:
        private string _valid = "";
        private void textBox1[B][COLOR="SeaGreen"]_TextChanged[/COLOR][/B](object sender, EventArgs e)
        {
            int t;
            if (int.TryParse(this.textBox1.Text + "0", out t))
                this._valid = this.textBox1.Text;
            else
                this.textBox1.Text = this._valid;
        }
 
Last edited:

Zangetsu

I am the master of my Fate.
Another query. I have restricted entry of values in textBoxes to numerics only by using this-

Code:
private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).
use java script function for blocking keys which will much easier & faster than server-side validation :cool:
 
OP
dashing.sujay

dashing.sujay

Moving
Staff member
^^ its a windows app :p

Sujay, when are you initiating the calculation?

When I press "OK" button.

Code:
 private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (textBox1.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox1.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            else
            {
                if (Convert.ToInt32(textBox1.Text) > 0)
                {
                    MessageBox.Show("Please check the respective items after entering the quantity");
                }
            }
            
            
            textBox5.Text = Convert.ToString(rate_mango * qua1);

            if (checkBox2.Checked)
            {
                if (textBox2.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox2.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }

            textBox6.Text = Convert.ToString(rate_pineapple * qua2);

            if (checkBox3.Checked)
            {
                if (textBox3.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox3.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            textBox7.Text = Convert.ToString(rate_apple * qua3);

            if (checkBox4.Checked)
            {
                if (textBox4.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox4.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            textBox8.Text = Convert.ToString(rate_banana * qua4);
            textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text));
        }

Its WIP still, making changes as per above suggestions.
 

nbaztec

Master KOD3R
When I press "OK" button.

Code:
 private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (textBox1.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox1.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            else
            {
                if (Convert.ToInt32(textBox1.Text) > 0)
                {
                    MessageBox.Show("Please check the respective items after entering the quantity");
                }
            }
            
            
            textBox5.Text = Convert.ToString(rate_mango * qua1);

            if (checkBox2.Checked)
            {
                if (textBox2.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox2.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }

            textBox6.Text = Convert.ToString(rate_pineapple * qua2);

            if (checkBox3.Checked)
            {
                if (textBox3.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox3.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            textBox7.Text = Convert.ToString(rate_apple * qua3);

            if (checkBox4.Checked)
            {
                if (textBox4.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox4.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            textBox8.Text = Convert.ToString(rate_banana * qua4);
            textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text));
        }

Its WIP still, making changes as per above suggestions.

For the love of God and your own good, please name your controls.
 
OP
dashing.sujay

dashing.sujay

Moving
Staff member
Update: I have made some changes:

Code:
 if (checkBox1.Checked)
            {
                if (textBox1.Text != "")
                {
                    qua1 = Convert.ToInt32(textBox1.Text);
                }
                else
                {
                    MessageBox.Show("Please enter a quantity");
                }
            }
            else
            {
                if (textBox1.Text != "")
                {
                    if (Convert.ToInt32(textBox1.Text) > 0)
                    {
                        MessageBox.Show("Please check the respective boxes after entering the values");
                    }
                    else
                    {
                        MessageBox.Show("Please check the fruits you want and enter the respective quantity");
                    }
                }

How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.

else
{
MessageBox.Show("Please check the fruits you want and enter the respective quantity");
}

I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?

Some more queries:

1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.

2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if I swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?

For the love of God and your own good, please name your controls.

I thought to do it in starting then skipped it :oops:

It can help you:
*imgur.com/sowmu.png
 

nbaztec

Master KOD3R
How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.
Your flow of control can use plenty of optimization but I'm guessing this exercise is rather a simple once, so just let it be.

I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?
Don't quite get you.

1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.
You're assigning the value not checking (use ==)

2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?

This is called short-circuit evaluation, been around since the days of C (if not Pascal too).
Basically it says if the first expression evaluates to false in a logical AND then other expressions do not need to be checked, same goes for logical OR.
You need to work on some basics first, take this C example and fire it up to notice the differences.
Code:
#include <stdio.h>

int foo()
{
   printf("foo");
   return 0;
}

int bar()
{
   printf("bar");
   return 1;
}

int main()
{
   foo() && bar();	// Says foo
   printf("\n");
   bar() && foo();	// Says barfoo
   printf("\n");
   foo() || bar();	// Says foobar
   printf("\n");
   bar() || foo();	// Says bar
   printf("\n");
   return 1;
}
 

RCuber

The Mighty Unkel!!!
Staff member
first you need to do the validations separately.

Code:
string Str = textBox1.Text.Trim();
int Num;

bool isNum = Int32.TryParse(Str, out Num);

if (!isNum)
{
MessageBox.Show("Please enter numeric only");
return; 
}
else
{
//continue your program
}
 
OP
dashing.sujay

dashing.sujay

Moving
Staff member
nbaztec said:
You need to work on some basics first

Yeah :(

Charan said:
first you need to do the validations separately.

For all textBoxes ?


PS: Thanks to all for helping me :), especially nbaztec, you rock buddy :thumbs:

What is Trim used for? (I can't understand it by explanation of intellisense. :| )

Explain this line please:
Code:
bool isNum = Int32.TryParse(Str, out Num);

I mean what its doing? TryParse is for ?

PS: I'm a newbie in this, so hold on your asses long please :p
 

RCuber

The Mighty Unkel!!!
Staff member
For all textBoxes ?
Yes, for every textbox you need to do validation. or you can write a function to do this. ill give a sample soon.

What is Trim used for? (I can't understand it by explanation of intellisense. :| )

trim is used to remove white spaces from a string
Explain this line please:
Code:
bool isNum = Int32.TryParse(Str, out Num);

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

I mean what its doing? TryParse is for ?


if the string is a number then the statement will convert the string to numeric and place it in "Num" variable. it will then return "true" to isNum Variable.

incase the string is not a numeric then "Num" will have "null" and return value will be "false".

Int32.TryParse Method (String, Int32) (System)

EDIT: BTW .. the "out" keyword.. its like "ref" keyword, only thing is that "out" doesn't require the variable to be initialized.
 
Last edited:

Zangetsu

I am the master of my Fate.
@dashing.sujay: can u post the scenario of validation u need when clicking submit button?
so we can optimise the code more.
 
OP
dashing.sujay

dashing.sujay

Moving
Staff member
I guess I am validating all the textboxes separately. All the validations are done on clicking "OK" button, or am I taking it wrong?
 

RCuber

The Mighty Unkel!!!
Staff member
^^what you are doing is fine for a beginner. you need to learn the basic things your self.. once you are a little comfortable with the language, you can go ahead learning advanced techniques.

don't get worried if you are getting errors. try to check the flow once or twice before posting here.. we can help you without any problem,but that's not the point.. you need to learn about the issues which come up when you are coding.
 

Zangetsu

I am the master of my Fate.
I guess I am validating all the textboxes separately. All the validations are done on clicking "OK" button, or am I taking it wrong?

I mean to put down what type of validation u need as point here

e.g: mandatory fields,blank check,invalid no etc.

just like a client requirement in a project
 
Top Bottom