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

113 Views Asked by At

enter image description here

Hello I am still confuse to this how can I get my listbox items and when I click every checklistboxes and I want to add the numbers and display in the textbox. for example I check the checklistbox index 1 which contains 300 it display in the textbox. Then I check also my index 2 of checkboxlist contains 100 then it display 400. Then if I check my index 3 of my checkboxlist contains 200 it display 600 in the checkbox.

My code:

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;

            }
        }


    }



}
}
2

There are 2 best solutions below

0
On BEST ANSWER

you can sum listbox items as this . After , you can set the total to 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();
2
On

This code might get your job done. There are still better ways to do what you are looking for. But, this can be a good solution too! Considering your textbox name as 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();
}