Search code examples
c#winformstextboxlabel

Textbox to Label errors in C#


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

Solution

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