简体   繁体   English

C# 中的 Label 错误的文本框

[英]Textbox to Label errors in C#

I am building a WinForm in C# and have no clue what I am doing.我正在 C# 中构建一个 WinForm 并且不知道我在做什么。 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.我很确定这是因为它返回到空白 state 并尝试在其中放入 If 语句,但由于 Int 或 String 类型而不断出错。 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 ;
    }

Use TryParse when dealing with input from users that may be invalid entries.在处理可能是无效条目的用户输入时使用 TryParse。

if (int.TryParse(txt_WeightRemain.Text, out var rw))
{
    // valid int
}
else
{
    // does not represent an int
}

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.因为这样,如果文本框为空,它将为您提供值 0,而不是 null 或空字符串。

When using convert and the value is empty then it will give such an error.当使用 convert 并且值为空时,它会给出这样的错误。

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对不起,可能英语不好,只是想帮忙

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM