c# 如何获取我的列表框项并在我按下检查列表框时快速添加它

c# how can i get my listbox item and add it quickly when i pressed checklistboxes

你好,我仍然对此感到困惑,我如何才能获得我的列表框项目以及当我单击每个检查列表框时我想添加数字并显示在文本框中。例如,我检查了包含 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;

            }
        }


    }



}
}

此代码可能会帮助您完成工作。还有更好的方法来做你正在寻找的事情。但是,这也是一个很好的解决方案!将您的文本框名称考虑为 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();
}

您可以这样对列表框项目求和。之后,可以将总数设置为textbox

        int total = 0;
        for (int i = 0; i < listBox2.Items.Count; i++)
        {
            total = total+ int.Parse(listBox2.Items[i].ToString());
        }
        textBox1.Text = total.ToString();