2

在此处输入图像描述

您好,我仍然对此感到困惑,如何获取我的列表框项目以及当我单击每个复选框时,我想添加数字并显示在文本框中。例如,我检查了包含 300 的复选框索引 1,它显示在文本框中。然后我检查我的复选框列表的索引 2 包含 100,然后它显示 400。然后,如果我检查我的复选框列表的索引 3 包含 200,它在复选框中显示 600。

我的代码:

namespace ggg
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();


    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        listBox1.Items.Clear();
        listBox2.Items.Clear();
        textBox1.Clear();
        foreach (string s in checkedListBox1.CheckedItems)
        listBox1.Items.Add(s);
        foreach (int i in checkedListBox1.CheckedIndices)
        {
            if (i == 0)
            {
                listBox2.Items.Add(300);
                decimal total = 300;
                textBox1.Text += total;
            }
            if (i == 1)
            {
                listBox2.Items.Add(100);
                decimal total = 100;
                textBox1.Text += total;
            }
            if (i == 2)
            {
                listBox2.Items.Add(200);
                decimal total = 200;
                textBox1.Text += total;

            }
        }


    }



}
}
4

2 回答 2

1

您可以将列表框项目总结为 this 。之后,您可以将总计设置为文本框

        int total = 0;
        for (int i = 0; i < listBox2.Items.Count; i++)
        {
            total = total+ int.Parse(listBox2.Items[i].ToString());
        }
        textBox1.Text = total.ToString();
于 2017-09-11T08:52:25.860 回答
0

此代码可能会完成您的工作。还有更好的方法来做你正在寻找的东西。但是,这也可以是一个很好的解决方案!将您的文本框名称视为myTextBox

private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int sum = 0; // Add a variable to capture the sum

    listBox1.Items.Clear();
    listBox2.Items.Clear();
    textBox1.Clear();
    foreach (string s in checkedListBox1.CheckedItems)
    listBox1.Items.Add(s);
    foreach (int i in checkedListBox1.CheckedIndices)
    {
        if (i == 0)
        {
            listBox2.Items.Add(300);
            sum += 300; // Add the value to sum
        }
        if (i == 1)
        {
            listBox2.Items.Add(100);
            sum += 100; // Add the value to sum
        }
        if (i == 2)
        {
            listBox2.Items.Add(200);
            sum += 200; // Add the value to sum
        }
    }

    // Finally, show the sum in text box
    myTextBox.Text = sum.ToString();
}
于 2017-09-11T08:48:29.077 回答