0

我有一个问题,listview我无法计算特定列的总和。

在我的项目中,我正在从 excel 文件中读取一些信息到 . ListView,然后通过执行一些操作来处理这些信息。

现在,当我阅读信息时,ListView我无法计算特定列的总和,函数是:-

private void button12_Click(object sender, EventArgs e)
{

    int iSum = 0;
    foreach (ListViewItem o in this.lsvMain.Items )
    {
        iSum = iSum + Convert.ToInt16(o.SubItems[8].Text);
        textBox1.Text = iSum.ToString();
    }

出现错误消息:FormatException 未处理(输入字符串的格式不正确)。它指示 (iSum..) 行。

没有任何字符串,所有信息都是整数!

4

3 回答 3

0

我猜你有以下问题之一:

int aNumber = Convert.ToInt16("15.6"); //throws format exception because of decimal value
int anotherNumber = Convert.ToInt16(""); //throws format exception because there is nothing to convert
int yetAnotherNumber = Convert.ToInt16("-23.00"); //throws format exception because of .00

我猜您正在读取 excel 文件中的数字并保留它们的字符串表示形式。

如果该列的格式为数字,我猜所有数字都表示为“X.00”或类似的,因此会导致您的FormatException

于 2013-02-03T22:34:18.310 回答
0

当您尝试Parse(或Convert)将某些东西发送到时,您会收到该错误Integer,而Integer.

例如

var anIntegerValue = Convert.ToInt16("a");

将导致异常:

FormatException:输入字符串的格式不正确。

将调试器附加到您的程序并检查您从列表框中检索的值。它会让你大吃一惊:)。

Daniel 提出的示例将导致同样的问题。int.Parse()or Int32.Parseor or Convert.Int16orConvert.Int32都将导致相同的异常。

于 2013-02-03T21:52:14.120 回答
0
private void button12_Click(object sender, EventArgs e)
{
    int sum = 0;

    foreach (ListViewItem o in lsvMain.Items)
    {
        int value;
        if (int.TryParse(o.SubItems[8].Text, out value))
            sum += value;
    }

    textBox1.Text = sum.ToString();
}
于 2013-02-03T21:43:46.090 回答