读取文件并存储到数组中并在文本框中显示总和

时间:2016-09-29 20:03:36

标签: c# asp.net visual-studio c#-4.0

我试图从文件中获取数据并将它们存储在一个数组中,然后在列表框中显示数据,然后求和,并将其显示在文本框中。这是我的代码,但它不起作用。我不确定我做错了什么。

private void findClick(object sender, EventArgs e)
{
   int sum;
   using (OpenFileDialog ofd = new OpenFileDialog())
   {
       if (ofd.ShowDialog() == DialogResult.OK)
       {
            using (StreamReader InputFile = new StreamReader(ofd.FileName))
            {
                while (InputFile.EndOfStream == false)
                {
                    int[] array = new int[listBox.Items.Count];
                    for (int i = 0; i < listBox.Items.Count; i++)
                    {
                        // array[i] = Convert.ToInt32(listBox.Items[i].ToString());
                        array[i] = int.Parse(listBox.Items[i].ToString());
                        sum = array.Sum();
                        TotalAmtlabel.Text = sum.ToString("N0");

                        TotalNumberslabel.Text = listBox.Items.Count.ToString();
                        TotalAmountlabel.Text = string.Format("{0:N0}", sum);
                   }
               }  
           }
       }
   }
}

2 个答案:

答案 0 :(得分:2)

listBox.Items.AddRange(File.ReadAllLines(ofd.FileName));

答案 1 :(得分:1)

尝试此操作并根据您的需要进行修改:

string[] amounts = File.ReadAllLines(ofd.FileName);
int currentSum = 0;
int totalSum = 0;
ListItem[] amountItems = new ListItem[amounts.Length];
for (int i = 0; i < amounts.Length; i++)
{
     if (int.TryParse(amounts[i], out currentSum))
     {
         totalSum += currentSum;
     }
     amountItems[i] = amounts[i];
}
listBox.Items.AddRange(amountItems);
TotalAmountlabel.Text = string.Format("{0}", totalSum);

您还可以使用数据源来绑定列表。请至少通过以下MSDN参考文献了解安全注意事项:

  1. ListItem
  2. ListBox