I am building a WinForm in C# and have no clue what I am doing. I have made it this far and this section is working but after entering numbers into the textbox and then removing them to change them I get an "Input string was not correct format" error. I am pretty sure this is because it is returning to a blank state and have tried putting an If statement in but keep getting errors on that because of Int or String type. How can I handle this and I am sure this is not the easiest or best way to do it but its how I got this working so far. Thanks,
private void txt_RP7_TextChanged(object sender, EventArgs e)
{
int rw = Convert.ToInt32(txt_WeightRemain.Text);
int ld = Convert.ToInt32(txt_LayerD.Text);
int pl = rw * ld / 100;
int rp = Convert.ToInt32(txt_RP7.Text);
int rwr = pl * rp / 100;
string rwrs = rwr.ToString();
lbl_RW7.Text = rwrs ;
}
CodePudding user response:
Use TryParse when dealing with input from users that may be invalid entries.
if (int.TryParse(txt_WeightRemain.Text, out var rw))
{
// valid int
}
else
{
// does not represent an int
}
CodePudding user response:
Try to not using Convert. Try using
int.TryParse(txt_WeightRemain.text, out int rw) int _rw = rw
Why? Because with that, if the text box is empty it will give you 0 for the value, not null or empty string.
When using convert and the value is empty then it will give such an error.
And try to makes codes more safety to avoid the divison by zero error. Basic math for that.
Sorry for may bad english, just try to help