# C#: Exception handling(?)



## dashing.sujay (Jul 29, 2012)

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.


```
[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-


```
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 (Jul 29, 2012)

why not change * if (Convert.ToInt32(textBox1.Text) > 0)*
to *if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0)*


----------



## arpanmukherjee1 (Jul 29, 2012)

Change this


dashing.sujay said:


> ```
> private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
> {
> e.Handled = !char.IsDigit(e.KeyChar);
> ...



to something 


```
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 (Jul 29, 2012)

dashing.sujay said:


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

```
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 :

```
int.Parse(value);
```

or better, simply use:

```
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);
     }
```




dashing.sujay said:


> ```
> private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
> {
> e.Handled = !char.IsDigit(e.KeyChar);
> ...


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):


```
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;
        }
```


----------



## Zangetsu (Jul 30, 2012)

dashing.sujay said:


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


use java script function for blocking keys which will much easier & faster than server-side validation


----------



## dashing.sujay (Jul 30, 2012)

^I don't know JS.


----------



## RCuber (Jul 30, 2012)

^^ its a windows app  

Sujay, when are you initiating the calculation?


----------



## nbaztec (Jul 30, 2012)

Zangetsu said:


> use java script function for blocking keys which will much easier & faster than server-side validation



I'm guessing it's a Windows Form Application.


----------



## Zangetsu (Jul 30, 2012)

^Oops...my bad didn't saw the Messagebox


----------



## dashing.sujay (Jul 30, 2012)

RCuber said:


> ^^ its a windows app
> 
> Sujay, when are you initiating the calculation?



When I press "OK" button.


```
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 (Jul 30, 2012)

dashing.sujay said:


> When I press "OK" button.
> 
> 
> ```
> ...



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


----------



## dashing.sujay (Jul 30, 2012)

Update: I have made some changes:


```
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?



nbaztec said:


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



I thought to do it in starting then skipped it 

It can help you:


Spoiler



*imgur.com/sowmu.png


----------



## nbaztec (Jul 30, 2012)

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

```
#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 (Jul 30, 2012)

first you need to do the validations separately.


```
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
}
```


----------



## dashing.sujay (Jul 30, 2012)

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 

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

Explain this line please: 
	
	



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


----------



## RCuber (Jul 30, 2012)

> 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:
> 
> 
> 
> ...





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


----------



## Zangetsu (Jul 30, 2012)

@dashing.sujay: can u post the scenario of validation u need when clicking submit button?
so we can optimise the code more.


----------



## dashing.sujay (Jul 30, 2012)

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 (Jul 30, 2012)

^^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 (Jul 30, 2012)

dashing.sujay said:


> 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


----------



## dashing.sujay (Jul 30, 2012)

RCuber said:


> ^^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.



Roger that! 



Zangetsu said:


> 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



Let me complete it and I'll post it if any issue arises.


----------



## RCuber (Jul 30, 2012)

dashing.sujay said:


> Roger that! .



lets rescue Sid first and then we will get Roger.


----------



## gopi_vbboy (Jul 30, 2012)

Welcome to world of c#.

So here are few code suggestions-
1.Always have some good naming conventions.This helps 
to improve code readability
Eg-chkFruits,nMangoes,etc

2.You can use String.Empty instead of "" for readability

3.I think as you want to validate four times using same 
logic.A functions will make code tidy.

Alternate way as per OOPS ideology
 is creating a validation class for you objects 
which is pretty high level for now.


Like

```
public void ValidateControlandAssign(CheckBox targetChkbox,TextBox tValue,TextBox tAssign,int rate )
            {
             private const string senterqty="Please enter a quantity";
			 private const string scheck="Please check the respective items after entering the quantity");
             private int tempval;
            if (targetChkbox.Checked)
            {
                if (tValue.Text != String.Empty)
				tempval = Convert.ToInt32(tvalue);
                else 
				MessageBox.Show(senterqty);
                
            }
            else
            {
                if (Convert.ToInt32(tValue.Text) > 0)
                    MessageBox.Show(scheck);               
            
            }			
			tAssign.Text= = Convert.ToString(rate * tempval);
             }



			 
private void button1_Click(object sender, EventArgs e)
        {
		..
		//as per your code call
		//observe how  names of control of your code  doesnt make sense except mango
		ValidateControlandAssign(checkBox1,textBox1,textBox5.Text, rate_mango);
		..
          }
```

4.Remove {} for single statements of if.

```
if (true) singlestatment;
else singlestatment;
```
5.Dont hardcode strings.Put it in either config file
or constants.



Spoiler





```
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));
        }
```




6.You can also use
Int.TryParse for readability


----------



## noob (Jul 30, 2012)

Have not read the complete thread but seen this in condition statement



> textBox1.Text != ""




Instead use this



> IsNullOrWhiteSpace or IsNullOrEmpty



*stackoverflow.com/questions/6976597/string-isnulloremptystring-vs-string-isnullorwhitespacestring

String.IsNullOrWhiteSpace Method (System)


----------



## nbaztec (Jul 30, 2012)

There is absolutely no need for checking String to be empty, the reason being there are only 2 equivalence classes - Correct Input and Incorrect Input and an empty string is the same as an incorrect numeric string.

@ds_ 
As I have earlier demonstrated the use of int.TryParse(), I suggest you instead use int.Parse() and handle the exception.

The most crude form of it would look like:


```
public void buttonOk_Click()
{
     try {
          this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1;
          this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2;
          this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3;
          ....
          CalculateTotal();
     } catch(FormatException) {
        MessageBox.Show("Only numbers are allowed")
     }
}
```

This way the calculation will cease once it detects one of the inputs as Invalid, I'd show you a much, much better way of handling things like these (using foreach and Controls property) but it'd be an overkill for now.

P.S. There is no need for Trim() here since TryParse()/Parse() trims it anyway.


----------



## dashing.sujay (Jul 30, 2012)

gopi_vbboy said:
			
		

> So here are few code suggestions-
> 1.Always have some good naming conventions.This helps
> to improve code readability
> Eg-chkFruits,nMangoes,etc
> ...



Thanks for your inputs but what's your take on nbaztec's opposition for 2nd point.

PS: Your 3rd and 5th point bounced my head 

@nbaztec: Working on it buddy 

Any views for this: C# int.Parse Optimization

Ok, am almost done, one query.

When I write else like 

```
else;
```

it gives _Possibly mistaken empty statement_ warning. (runs fine though)

But when I write like:


```
else {}
```

It says fine. 

Everything fine now. Final queries:

Code of OK (submit) button:



Spoiler





```
private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    qua1 = int.Parse(textBox1.Text);
                }
            }
            else
            {
                if (textBox1.Text == "")
                {
                    
                }
                else
                {
                    if (int.Parse(textBox1.Text) > 0)
                        MessageBox.Show("Please check the respective boxes after entering the values");
                    else { }
                }
                
            }
            
            
            textBox5.Text = Convert.ToString(rate_mango * qua1);

            if (checkBox2.Checked)
            {
                if (textBox2.Text == "")
                {
                    MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    qua2 = int.Parse(textBox2.Text);
                }
            }
            else
            {
                if (textBox2.Text == "")
                {
                    
                }
                else
                {
                    if (int.Parse(textBox2.Text) > 0)
                        MessageBox.Show("Please check the respective boxes after entering the values");
                    else { }
                }
                
            }

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

            if (checkBox3.Checked)
            {
                if (textBox3.Text == "")
                {
                    MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    qua3 = int.Parse(textBox3.Text);
                }
            }
            else
            {
                if (textBox3.Text == "")
                {
                    
                }
                else
                {
                    if (int.Parse(textBox3.Text) > 0)
                        MessageBox.Show("Please check the respective boxes after entering the values");
                    else { }
                }
                
            }
            textBox7.Text = Convert.ToString(rate_apple * qua3);

            if (checkBox4.Checked)
            {
                if (textBox4.Text == "")
                {
                    MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    qua4 = int.Parse(textBox4.Text);
                }
            }
            else
            {
                if (textBox4.Text == "")
                {
                    
                }
                else
                {
                    if (int.Parse(textBox4.Text) > 0)
                        MessageBox.Show("Please check the respective boxes after entering the values");
                    else { }
                }
                
            }
            textBox8.Text = Convert.ToString(rate_banana * qua4);
            textBox9.Text = Convert.ToString(int.Parse(textBox5.Text) + int.Parse(textBox6.Text) + int.Parse(textBox7.Text) + int.Parse(textBox8.Text));
        }
```




Code of "Reset" button:



Spoiler





```
private void button2_Click(object sender, EventArgs e)
        {
            checkBox1.Checked = false;
            checkBox2.Checked = false;
            checkBox3.Checked = false;
            checkBox4.Checked = false;
            textBox1.Text = "0";
            textBox2.Text = "0";
            textBox3.Text = "0";
            textBox4.Text = "0";
            textBox5.Text = "0";
            textBox6.Text = "0";
            textBox7.Text = "0";
            textBox8.Text = "0";
            textBox9.Text = "0";
            int qua1 = 0;
            int qua2 = 0;
            int qua3 = 0;
            int qua4 = 0;
        }
```




1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?

2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.

This screenie of my app may help you overcoming my bad naming convention.


Spoiler



*imgur.com/sowmu.png



One more question:

I applied *E.Handled *restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?


----------



## nbaztec (Jul 30, 2012)

dashing.sujay said:


> Any views for this: C# int.Parse Optimization


It's optimization at the cost of error checking. It won't throw errors on invalid inputs like "12s2". It uses the age-old technique of converting ASCII numbers to decimal.



dashing.sujay said:


> When I write else like
> 
> ```
> else;
> ...


This is compiler check. It does it since programmers sometimes tend to misplace ';' like:

```
if(condition);           // Erroneous semi-colon
      doSomeWork();
```
If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive  *#pragma warning disable 642*. Alternatively you can exclude that optional else clause



> 1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?


Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.



> 2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.


I'm guessing some errand variables you failed to reset.



> I applied *E.Handled *restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?


Possible if you copied-pasted those text-boxes from the first one.


----------



## dashing.sujay (Jul 31, 2012)

> If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive #pragma warning disable 642. Alternatively you can exclude that optional else clause



Do I really need that fuss? I just included the braces.



> Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.



What is try-catch approach ? I didn't got it at all.



> I'm guessing some errand variables you failed to reset.



There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.



> Possible if you copied-pasted those text-boxes from the first one.



No, I didn't.

PS: thanks for all the help


----------



## Zangetsu (Jul 31, 2012)

dashing.sujay said:


> What is try-catch approach ? I didn't got it at all.



to catch any errors if it occurs & handle those in structured way....
catching error & displaying the user about the error


----------



## nbaztec (Jul 31, 2012)

dashing.sujay said:


> Do I really need that fuss? I just included the braces.


You can remove the else clause altogether, it's optional.



> What is try-catch approach ? I didn't got it at all.




```
public void buttonOk_Click()
{
     try {
          this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1;
          this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2;
          this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3;
          ....
          CalculateTotal();
     } catch(FormatException) {
        MessageBox.Show("Only numbers are allowed")
     }
}
```



> There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.


The code seems fine, but surely there's something incorrect in the code itself.



> No, I didn't.


Or you selected all the boxes, but that's irrelevant. Just select all the textboxes and remove the definition, then put it for the correct textbox.


----------



## dashing.sujay (Aug 1, 2012)

> Or you selected all the boxes, but that's irrelevant. Just select all the textboxes and remove the definition, then put it for the correct textbox.



Actually I wanted to work it on all boxes and its working without my effort lol 

I experienced same case in a program written by one of my friend where he made a sample calci to input two nos and print +,-,*,/ on clicking buttons. But when I saw the code, there was only "sum", nothing else.


----------

