简体   繁体   English

C#计算后更新textBox并在其中转换数据时出错

[英]C# Error in updating textBox and converting data in it after calculation

Im kinda new to C# and hawing a problem with a code. 我对C#有点陌生,并且对代码有疑问。

            private void tbSold_TextChanged(object sender, TextChangedEventArgs e)
    {
        tbSold.Text = tbSold.Text.Replace(',', '.');
        tbSold.Select(tbSold.Text.Length, 0);


        double BO = Convert.ToDouble(tbBought.Text);
        double SO = Convert.ToDouble(tbSold.Text);
        double TOT = ((SO / BO) * 100);
        tbTotal.Text = Convert.ToString(TOT +"%");
    }

Now the explanation and the question. 现在说明和问题。 The first part of the code is for replacing the coma with the dot so I can insert the data in SQLExpress. 代码的第一部分是用点替换逗号,因此我可以在SQLExpress中插入数据。

But I also want to hawe the percantage displayed in tbTotal. 但我也想了解tbTotal中显示的性能。 Im hawing 2 problems here. 我在这里有2个问题。 One is that I get a error if I delete all the characters in the tbSold textBox. 一种是如果删除tbSold文本框中的所有字符,则会出现错误。 No matter If they were decimal or not ... and the second is that I dont get the corect value if there is a decimal value. 不管它们是否为十进制……第二个是如果有十进制值,我就不会获得corect值。

If I put the conversion in the buttonClick event for inserting in the database, I get my data inserted but getting the error afterwards. 如果将转换放入buttonClick事件中以插入数据库中,则会插入数据,但之后会出现错误。

I now Im probably missing something simple but cant figure it out 我现在可能会遗漏一些简单但无法弄清楚的东西

You cannot convert a blank string ( "" ) to a double - you will get a FormatException . 您不能将空字符串( "" )转换为FormatException您将获得FormatException I would add some checking for blank strings (and for 0 in the Bought field: 我会为空白字符串添加一些检查(并在Bought字段中添加0

private void tbSold_TextChanged(object sender, TextChangedEventArgs e)
{
    tbSold.Text = tbSold.Text.Replace(',', '.');
    tbSold.Select(tbSold.Text.Length, 0);


    double BO; 
    bool boughtPrased = double.TryParse(tbBought.Text, out BO);
    // what should you do if the parse fails?

    double SO;
    bool soldParsed = double.Parse(tbSold.Text, out SO);
    // what should you do if the parse fails?

    double TOT = (SO / BO);  // convert to percentage in format below
    // what do you do if BO is 0?

    // display as percentage with two decimal digits
    tbTotal.Text = string.Format("{0:P2}",TOT);
}

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

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