Hi there guys I have a question. How do I put values on items in a comboBox and compute its total?

You can look at my attachment for your reference.
Normal Subjects are worth 2 units and Subjects with "-Lab" are worth 1 unit each.
Now when I check subjects in the combobox it automatically adds up the total of what I have checked to my total units textbox. How do I do that? Help me please... thank you

Recommended Answers

All 2 Replies

Here is an example I wrote using a CheckedListBox, a Label, and a Button:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            List<MyData> data = new List<MyData>();

            checkedListBox1.Items.Clear();
            for (int i = 0; i < 10; i++) {
                data.Add(new MyData(String.Format("Item #{0}", i), i));
            }

            checkedListBox1.DataSource = new BindingSource(data, null);
            checkedListBox1.DisplayMember = "Name";
            checkedListBox1.ValueMember = "Value";
        }

        private void button1_Click(object sender, EventArgs e) {
            int total = 0;

            foreach (int i in checkedListBox1.CheckedIndices) {
                total += ((MyData)(checkedListBox1.Items[i])).Value;
            }

            label1.Text = total.ToString();
        }
    }

    public class MyData {
        public int Value { get; private set; }
        public String Name { get; private set; }

        public MyData(String name, int value) {
            Value = value;
            Name = name;
        }
    }
}

You may use this piece of code to get what you want:

int total = 0;
            string s = "";
            for (int x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++)
            {
                s = checkedListBox1.CheckedItems[x].ToString();
                if (s.IndexOf("-Lab") != -1)
                {
                    total += 1;
                }
                else
                {
                    total += 2;
                }
            }
            textBox1.Text = total.ToString();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.