Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When I remove number from textBox5, the code errors out;
int R = Convert.ToInt32(textBox4.Text);
//int I = Convert.ToInt32(textBox5.Text);

//int E = R * I;

//textBox6.Text = E.ToString();

The second way I tried is below: Both codes error out when I remove number and try to put in a new number.

int R = int.Parse(textBox4.Text);
int I = int.Parse(textBox5.Text);

int E = R * I;

textBox6.Text = E.ToString();

What I have tried:

The two ways in the description
Posted
Updated 30-Nov-17 3:10am
Comments
Richard MacCutchan 30-Nov-17 8:56am    
What sort of error?Please give proper details of the problem.

Convert.ToInt32 and int.Parse are only suitable if you know the text can be converted to an int, as you are working with user input you don't know if it is valid, so use int.TryParse instead.

int R = 0;
int I = 0;

if (!int.TryParse(textBox4.Text.Trim(), out R))
{
    // if the code gets here the conversion to int failed
    // you can show a message to the user, or give R a default value
    // do whatever your code requires

    R = 0;
}

if (!int.TryParse(textBox5.Text.Trim(), out I))
{
    // if the code gets here the conversion to int failed
    // you can show a message to the user, or give I a default value
    // do whatever your code requires

    I = 0;
}

int E = R * I;
 
Share this answer
 
When you remove the number from the textbox, then an empty string is passed to the ToInt32 method, which raises the error because it cannot convert an empty string to a integer value.
Int32.Parse method does as well.
You have several options:
- allow input of empty strings in the TextBox and interpret empty strings as a default value of zero.
- handle the Validating event of the TextBox and do not allow to loose focus until there is an integer value in there (not very user friendly).
- have an error provider spotting the missing value.

There is one rule that is never blindly trust user inputs, always assume there will be input errors, so code to handle all test cases. The TryParse method could be a good choice to test for input values. A better option than the Convert class which is not a very good tool for the task at hand, anyway.

Hope this helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900