尝试添加并显示ListBox中的值的总和...获取错误:System.InvalidCastException:'指定的强制转换无效。'

时间:2017-05-18 15:46:54

标签: c# arrays sum

我试图获取列表框中所有值的总和,并且我想在文本框中显示结果。当我运行程序并单击按钮时,我收到以下错误:System.InvalidCastException:'指定的强制转换无效。'

    private void readButton_Click(object sender, EventArgs e)
    {
        int counter = 0;
        string line;
        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Harra\Documents\Visual Studio 2017\Projects\File Reader\Sales.txt");
        while ((line = file.ReadLine()) != null)
        {
            displayListBox.Items.Add(line);
            counter++;
        }
        {

            int intTotal = 0;
            int intCounter;
            double dblAdd;

            for (intCounter = 0; intCounter <= displayListBox.Items.Count - 1; intCounter++)

            {
                intTotal += Convert.ToInt32(displayListBox.Items[intCounter];
            }

            dblAdd = (double)intTotal;

            //trying to display total to textbox
            totalTextBox.Text = string.Format("{0:F}", dblAdd);
        }

    }

1 个答案:

答案 0 :(得分:0)

在你的评论和更多细节之后,我认为这应该有效:

private void readButton_Click(object sender, EventArgs e)
{
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Harra\Documents\Visual Studio 2017\Projects\File Reader\Sales.txt");
    double dblAdd = 0;
    while ((line = file.ReadLine()) != null)
    {
        displayListBox.Items.Add(line);
        dblAdd += Convert.ToDouble(line);
    }
    totalTextBox.Text = string.Format("{0:F}", dblAdd);
}