猿问

如何使用 TextBox 对 Listbox 中的所有数字求和?

我想对 a 中的所有值进行计数和求和ListBox。例如,我的ListBox: 4, 6, 1,中有以下值7。我当前的值是18. 如果我添加 a2和 a TextBox,我需要得到20,如果我添加5,我需要得到25总计。


如果我用下面的代码尝试它,它会给我一个完整的数字。


这是我的代码:


private void AddButton_Click(object sender, EventArgs e)

{

    decimal sum;

    listBox2.Items.Add(TextBox1.Text);

    TextBox1.Text = "";


    for (int i = 0; i < listBox2.Items.Count; i++)

    {

        sum += Convert.ToDecimal(listBox2.Items[i].ToString());

    }


    Label1.Text = sum.ToString();

}


莫回无
浏览 134回答 4
4回答

慕容森

您错过了初始化 sum 的默认值。在向变量sum = 0添加值之前赋值sumprivate void AddButton_Click(object sender, EventArgs e){&nbsp; &nbsp; decimal sum = 0;&nbsp; //Set sum = 0&nbsp; by default&nbsp; &nbsp; listBox2.Items.Add(TextBox1.Text);&nbsp; &nbsp; TextBox1.Text = "";&nbsp; &nbsp; for (int i = 0; i < listBox2.Items.Count; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //To check value of sum after each iteration, you can print it on console&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Sum =" +sum);&nbsp; &nbsp; &nbsp; &nbsp; sum += Convert.ToDecimal(listBox2.Items[i].ToString());&nbsp; &nbsp; }&nbsp; &nbsp; Label1.Text = sum.ToString();}

Qyouu

对不起,也许没有回答,但奇怪的是你的编译器没有告诉你初始化 sum。第二次我测试了您的代码,它按预期正常工作,这意味着如果问题不在 sum 变量中,那么您在其他地方对该字段进行了其他操作,因此您的代码无法正常工作。考虑到您对前人的评论,我也会这么说。在某些情况下(我知道这很有趣,但是)您的计算机上可能有病毒。核实。有一次我的数学实验室工作失败了,因为病毒中断了我的程序,所以它画了错误的图表!我知道:D

宝慕林4294392

需要将 sum 设置为 0,而且最好使用 foreach 而不是 Dotloop。private void AddButton_Click(object sender, EventArgs e) {&nbsp; &nbsp; decimal sum = 0;&nbsp; &nbsp; listBox2.Items.Add(TextBox1.Text);&nbsp; &nbsp; TextBox1.Text = "";&nbsp;&nbsp; &nbsp; foreach (string s in listBox2) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; sum += Convert.ToDecimal(s);&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; Label1.Text = sum.ToString();&nbsp;}

眼眸繁星

&nbsp; &nbsp;private void button1_Click(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; var value = 0;&nbsp; &nbsp; &nbsp; &nbsp; listBox1.Items.Add(textBox1.Text);&nbsp; &nbsp; &nbsp; &nbsp; foreach (var item in listBox1.Items)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!int.TryParse(item.ToString(), out value))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum = sum + value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; label1.Text = sum.ToString();&nbsp; &nbsp; &nbsp; &nbsp; textBox1.Text = string.Empty;&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答