0

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 ;
    }
Wapalo
  • 5
  • 4
  • Does this answer your question? [How do I make a textbox that only accepts numbers?](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – Wei Chen Chen Aug 31 '22 at 00:35

2 Answers2

0

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
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31
0

Try to not use 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 make your code more safe to avoid the divison by zero error. Basic math for that.

Sorry for my bad english, just trying to help.

Josef
  • 2,869
  • 2
  • 22
  • 23