"将字符串转换为DateTime"将字符串转换为Int16

时间:2016-05-11 01:51:21

标签: c# datetime

错误图片: n1

这与DateTime无关,所以我不知道为什么会不断出现,这是我正在使用的代码。当您在输入所需文本后按计算时,它应显示价格,然后计算折扣并最终显示最终价格。

错误附带的行 - 十进制价格= Convert.ToDecimal(txtPrice.Text);

txtPrice为空,或者更具体地说是只读,变量'价格'应该把它设置为100或我想要的if语句,对吗?

顺便说一下每个部分的价格不应该是100,不断改变代码以使错误消失所以我只是复制并粘贴了#34; price = 100;"所以我每次都不必输入不同的号码。

private void btnCalculate_Click(object sender, EventArgs e)
{
    int tenure = Convert.ToInt16(txtTenure.Text);
    string seatingType = txtLocation.Text;
    decimal discountPercent = .0m;
    decimal price = Convert.ToDecimal(txtPrice.Text);

    if (seatingType == "Main")
    {
        price = 100;

        if (tenure >= 6)
            discountPercent = .5m;
        else if (tenure >= 12)
            discountPercent = .75m;
        else if (tenure >= 24)
            discountPercent = 1.0m;
    }
    else if (seatingType == "Pit")
    {
        price = 100;

        if (tenure >= 12)
            discountPercent = .5m;
        else if (tenure >= 12)
            discountPercent = .75m;
        else if (tenure >= 24)
            discountPercent = 1.0m;
    }
    else if (seatingType == "Balcony")
    {
        price = 100;

        if (tenure >= 12)
            discountPercent = .5m;
        else if (tenure >= 12)
            discountPercent = .75m;
        else if (tenure >= 24)
            discountPercent = 1.0m;
    }

    decimal discountAmount = price * discountPercent;
    decimal finalPrice = price - discountAmount;

    txtFinalPrice.Text = finalPrice.ToString("c");

}

我使用的是教科书示例,一切看起来都很正确,不知道为什么会这样。 n2

2 个答案:

答案 0 :(得分:0)

int tenure = Convert.ToInt16(txtTenure.Text);

使用:

try
{
   int tenure = Convert.ToInt16(txtTenure.Text);
}
catch (FormatException e)
{
   ...report error...
}

此外,if语句在获得适当折扣之前退出。

您需要撤消它们并首先检查较低的金额:

if (seatingType == "Main")
{
    price = 100;

    if (tenure >= 24)
        discountPercent = .5m;
    else if (tenure >= 12)
        discountPercent = .75m;
    else
        discountPercent = 1.0m;
}

等...

正如你现在所做的那样,他们在达到适当的折扣因子之前就已经退出,并且不能处理少于6的任期。

答案 1 :(得分:0)

疑难解答提示只是基于特定类型的例外的提示。在您的情况下,转换DateTime字符串时发生FormatException错误是很常见的。这就是为什么Visual Studio会向您提示DateTime的原因。

https://msdn.microsoft.com/en-us/library/2ww37f14.aspx

关于您的错误,您无法将空字符串转换为数字。所以我建议你改变你的代码:

int price = Convert.ToInt16(txtPrice.Text)

int price;
if (decimal.TryParse(txtPrice.Text, out price) == false)
    price = 100;
相关问题