0

我正在尝试比较两个文本框以查看它们是否为空,但出现异常错误:

输入字符串的格式不正确

代码:

private void btncalc_Click(object sender, EventArgs e)
{
    try
    {
        int ina= int.Parse(txttea.Text);
        int inb= int.Parse(txtcoffee.Text);
        int inc = 0, ind = 0;
        if (this.txttea.Text == "" && this.txtcoffee.Text == "")  // this not working
        {
            MessageBox.Show("select a item");
            txttea.Focus();
        }
        if (cbxwithoutsugar.Checked)
        {
            inc = (ina * 20);
        }
        else
        {
            inc = (ina * 8);
        }
        if (cbxcoldcoffee.Checked)
        {
            ind = (inb * 10);
        }
        else
        {
            ind = (inb * 5);
        }
        txtamount.Text = (Convert.ToInt32(inc) + Convert.ToInt32(ind)).ToString();
    }
    catch (Exception a)
    {
        MessageBox.Show(a.Message);
    }
}
4

5 回答 5

2

您应该首先检查文本框是否为空,然后才尝试获取值。
另外,像这样使用String.IsNullOrEmpty

    if (String.IsNullOrEmpty(txttea.Text) || String.IsNullOrEmpty(txtcoffee.Text)) 
    {
        MessageBox.Show("select a item");
        txttea.Focus();
    }
    int ina= int.Parse(txttea.Text); // See comment below about TryParse
    int inb= int.Parse(txtcoffee.Text);
    int inc = 0, ind = 0;

此外,使用TryParse而不是 Parse (并且修剪始终是避免 WhiteSpace 的好主意):

int ina;
if (!Int32.TryParse(txttea.Text.Trim(), out ina))
{
   MessageBox.Show("Value is not a number");
}
于 2013-02-03T09:21:02.273 回答
2

尝试使用 TryParse 方法,因为如果有空格,您的代码将失败,使用 TryParse,您无需尝试捕获,只需将两个整数比较为零,例如:

int ina =0 , inb =0;

int.TryParse(txttea.Text, out ina);
int.TryParse(txtcoffee.Text, out inb);

if (ina == 0 && this.inb == 0)  // this not working
{

}
于 2013-02-03T09:22:57.293 回答
1

当您需要一个数字时,我建议您使用 NumericUpDown 而不是 TextBox。这样您就可以使用 Value 来获取咖啡和茶的数量。

private void btncalc_Click(object sender, EventArgs e)
{
    try
    {
        int ina= numtea.Value;
        int inb= numcoffee.Value;
        int inc = 0, ind = 0;
        if (ina == 0 && inb == 0)  // this not working
        {
            MessageBox.Show("select a item");
            numtea.Focus();
        }
        if (cbxwithoutsugar.Checked)
        {
            inc = (ina * 20);
        }
        else
        {
            inc = (ina * 8);
        }
        if (cbxcoldcoffee.Checked)
        {
            ind = (inb * 10);
        }
        else
        {
            ind = (inb * 5);
        }
        txtamount.Text = (inc + ind).ToString();
    }    
}

这是一个很好的用户友好的解决方案。

于 2013-02-03T09:25:43.247 回答
0

我有一种感觉,您指示为“不工作”的行不是问题,但整数解析是问题。异常不是可以从逻辑测试中抛出的异常,而是可以从格式错误的整数解析中抛出的异常。尝试注释掉解析行,看看错误是否仍然发生。

于 2013-02-03T09:20:59.740 回答
0

首先,您正在解析文本框的文本。然后你再次检查他们的文本值是否为空。这不是多余的吗?

如果文本区域中的文本不是数字,则应该存在解析异常。它将显示在消息框中。我认为您可以尝试放置一些记录语句来打印解析整数的值。

于 2013-02-03T09:22:51.473 回答