1

这是我的第一篇文章。我试图在 Visual C# 的选中列表框中进行多个总和。有 108 个数字,每行一个,我试图将选中的项目与其余的项目相加,并将其打印在文本框中。

我已经这样做了,但我认为这是不正确的。这实际上是求和,但也是数字本身和整个事物的 108 次

我想在复选框中添加选中的数字和其余数字。

private void button2_Click(object sender, EventArgs e)
{
   foreach(string checkednumber in checkedlistbox1.CheckedItems)
   {
      double x = Convert.ToDouble(checkednumber);

      double a = 0;
      for (double y = 0; y < checkedlistbox1.Items.Count; ++y)
      {
         foreach (string othernumbers in checkedlistbox1.Items)
         {
            double z = Convert.ToDouble(othernumbers);
            sum = x + z;
            string str = Convert.ToString(sum);
            listbox1.Items.Add(str);
         }
      }
   }  
}

谢谢你的帮助。

4

2 回答 2

2

您只想对已检查项目的数字求和?

double sum = 0;

foreach(object checkedItem in checkedlistbox1.CheckedItems)
{
    try 
    {
        sum += Convert.ToDouble(checkedItem.ToString()); 
    }
    catch (FormatException e) {} //catch exception where checkedItem is not a number

    listbox1.Items.Add(sum.ToString());
} 

您的问题非常不清楚,我不确定这是否是您想要的。

于 2013-04-16T15:30:49.960 回答
0

您也可以使用 linq 来实现它。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var result = from num in this.checkedListBox1.CheckedItems.OfType<string>()
                         select Convert.ToInt32(num);
            this.textBox1.Text = result.Sum().ToString();
        }
    }
}
于 2013-04-17T13:35:22.133 回答