Search code examples
c#formslistboxchecklistbox

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


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;

            }
        }


    }



}
}

Solution

  • 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();