locked
How to assign values to checkedlistbox items and sum these values RRS feed

  • Question

  • Hello,

    I am developing a VS 2005 C# windows form application such that I have a checkedlistbox with 5 items. I want to check 1, 2,3,4 or 5 items at a time.

    For example:

    Checkedlistbox item 1 = 5

    Checkedlistbox item 2 = 7

    Checkedlistbox item 3 = 4

    Checkedlistbox item 4 = 9

    Checkedlistbox item 5 = 2

    On a buttonclick event, If for instance I checked items 1,2 and 4, I want the sum of these values (i.e 21) displayed in textbox1.

    Many thanks.

    Thursday, November 8, 2012 5:11 AM

Answers

  • Viorel is correct in that you'll want to start by creating a type that can hold both the display value and the actual underlying value.  He provided a specific one for this case; I'd make a more generic one that can work with any two types:

    public class CheckBoxItem<K, V>
    {
        public CheckBoxItem(K displayValue, V hiddenValue)
        {
            DisplayValue = displayValue;
            HiddenValue = hiddenValue;
        }
    
        public K DisplayValue { get; private set; }
        public V HiddenValue { get; private set; }
    
    
        public override string ToString()
        {
            return DisplayValue == null ? "" : DisplayValue.ToString();
        }
    }

    Then adding a `Create` function can make creating them easier due to type inference of methods:

    public static CheckBoxItem<K, V> Create<K, V>(K displayValue, V hiddenValue)
    {
        return new CheckBoxItem<K, V>(displayValue, hiddenValue);
    }

    To create the CheckedListBox could look something like this:

    var list = new List<CheckBoxItem<string, int>>();
    list.Add(Create("Checkedlistbox item 1", 5));
    list.Add(Create("Checkedlistbox item 2", 7));
    //... add the rest
    
    CheckedListBox box = new CheckedListBox();
    box.Items.AddRange(list.Cast<object>().ToArray());
    Controls.Add(box);

    Once you have all of that summing the underlying values of all of the checked items is pretty trivial:

    int sum = box.CheckedItems.Cast<CheckBoxItem<string, int>>()
        .Sum(item => item.HiddenValue);
    @Everyone else in the thread, is it really that hard to comprehend that he wants to display something other than the underlying value?  This is just like how the `select` HTML tag works; there is a separate property for the text and underlying value for each item, and they're only occasionally identical.  In this case you need to do a bit of work to get there, but the concept is still simple enough.


    • Edited by servy42 Thursday, November 8, 2012 3:08 PM
    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 3:06 PM
  • try the following code:

    private void button3_Click(object sender, EventArgs e)
            {
                int Sum = 0;
                foreach (object _item in checkedListBox1.CheckedItems)
                {
                    Sum = Sum + (int)_item;
                }
            }
    

    thanks


    Hirendra Sisodiya from authorcode.com

    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 5:53 AM
  • private void button1_Click(object sender, EventArgs e)
            {
                double sum = 0.0;
    
                foreach (var item in checkedListBox1.CheckedIndices)
                {
                    sum += Convert.ToInt32(checkedListBox1.Items[(int)item]);
                }
                MessageBox.Show(sum.ToString());
            }

    我的博客园
    慈善点击,点击此处
    和谐拯救危机,全集下载,净化人心

    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 6:00 AM
  • for ease of work you can hard code the names of the textbox while reading the values based on checkboxes. In the button click, you can check each of the check nox, and get the value of associated textbox near to it.

    int iSum = 0;
    if (checkBox1.Checked == true)
        iSum = iSum + 1;
    if (checkBox1.Checked == true)
        iSum = iSum + 2;
    if (checkBox1.Checked == true)
        iSum = iSum + 3;
    if (checkBox1.Checked == true)
        iSum = iSum + 4;
    if (checkBox1.Checked == true)
        iSum = iSum + 5;
    textBox1.Text = iSum;

    or if you want to read the integer values present in the checkboxes, there should be som egeneric rules to find out form the name say last character of the name will be the the integer values.

    Else, you can assign the text to the checkboxes as the integer values.

    int iSum = 0;
    checkBox1.Text = "1"; // this you can do at the design page of the form also
    checkBox1.Text = "2"; // this you can do at the design page of the form also
    checkBox1.Text = "3"; // this you can do at the design page of the form also
    checkBox1.Text = "4"; // this you can do at the design page of the form also
    checkBox1.Text = "5"; // this you can do at the design page of the form also
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox1.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox2.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox3.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox4.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox5.Text);
    textBox1.Text = iSum;

    regards

    joon


    • Marked as answer by Topa 1 Monday, November 12, 2012 1:53 AM
    Thursday, November 8, 2012 2:37 PM

All replies

  • try the following code:

    private void button3_Click(object sender, EventArgs e)
            {
                int Sum = 0;
                foreach (object _item in checkedListBox1.CheckedItems)
                {
                    Sum = Sum + (int)_item;
                }
            }
    

    thanks


    Hirendra Sisodiya from authorcode.com

    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 5:53 AM
  • private void button1_Click(object sender, EventArgs e)
            {
                double sum = 0.0;
    
                foreach (var item in checkedListBox1.CheckedIndices)
                {
                    sum += Convert.ToInt32(checkedListBox1.Items[(int)item]);
                }
                MessageBox.Show(sum.ToString());
            }

    我的博客园
    慈善点击,点击此处
    和谐拯救危机,全集下载,净化人心

    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 6:00 AM
  • Hello and many thanks,

    So..... how do I write the code to asssign values to the checkeckedlistbox checked items, for example:

    Checkedlistbox item 1 = 5

    Checkedlistbox item 2 = 7

    Checkedlistbox item 3 = 4

    Checkedlistbox item 4 = 9

    Checkedlistbox item 5 = 2

    Thanks.

    Thursday, November 8, 2012 6:05 AM
  • Just drag and drop a CheckedListBox onto the WinForm and do this:

    CheckedListBox.Items.Add(5,false);
    ………………

    我的博客园
    慈善点击,点击此处
    和谐拯救危机,全集下载,净化人心

    Thursday, November 8, 2012 7:00 AM
  • If your control displays strings and you want to associate a number with each item, then instead of adding strings, define your own item like in this draft:

    class MyItem

    {

        public string Text;

        public int Number;

        public override string ToString() { return Text; }

    }

    Now when you iterate the items you will add the Number values.


    • Edited by Viorel_MVP Thursday, November 8, 2012 7:15 AM
    Thursday, November 8, 2012 7:14 AM
  • No one seemed to understand my request:

    I am developing a VS 2005 C# windows form application such that I have a checkedlistbox with 5 items. I want to check 1, 2,3,4 or all 5 items at a time.

    I also want to assign or associate numerical values to each item on checkedlistbox1.

    For example:

    Checkedlistbox item 1 = 5

    Checkedlistbox item 2 = 7

    Checkedlistbox item 3 = 4

    Checkedlistbox item 4 = 9

    Checkedlistbox item 5 = 2

    On a buttonclick event, If for instance I checked items 1,2 and 4, I want the sum of the assigned or associated numerical values (i.e 21) displayed in textbox1.

    Many thanks.

    Thursday, November 8, 2012 2:17 PM
  • for ease of work you can hard code the names of the textbox while reading the values based on checkboxes. In the button click, you can check each of the check nox, and get the value of associated textbox near to it.

    int iSum = 0;
    if (checkBox1.Checked == true)
        iSum = iSum + 1;
    if (checkBox1.Checked == true)
        iSum = iSum + 2;
    if (checkBox1.Checked == true)
        iSum = iSum + 3;
    if (checkBox1.Checked == true)
        iSum = iSum + 4;
    if (checkBox1.Checked == true)
        iSum = iSum + 5;
    textBox1.Text = iSum;

    or if you want to read the integer values present in the checkboxes, there should be som egeneric rules to find out form the name say last character of the name will be the the integer values.

    Else, you can assign the text to the checkboxes as the integer values.

    int iSum = 0;
    checkBox1.Text = "1"; // this you can do at the design page of the form also
    checkBox1.Text = "2"; // this you can do at the design page of the form also
    checkBox1.Text = "3"; // this you can do at the design page of the form also
    checkBox1.Text = "4"; // this you can do at the design page of the form also
    checkBox1.Text = "5"; // this you can do at the design page of the form also
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox1.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox2.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox3.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox4.Text);
    if (checkBox1.Checked == true)
        iSum = iSum + Int32.Parse(checkBox5.Text);
    textBox1.Text = iSum;

    regards

    joon


    • Marked as answer by Topa 1 Monday, November 12, 2012 1:53 AM
    Thursday, November 8, 2012 2:37 PM
  • Viorel is correct in that you'll want to start by creating a type that can hold both the display value and the actual underlying value.  He provided a specific one for this case; I'd make a more generic one that can work with any two types:

    public class CheckBoxItem<K, V>
    {
        public CheckBoxItem(K displayValue, V hiddenValue)
        {
            DisplayValue = displayValue;
            HiddenValue = hiddenValue;
        }
    
        public K DisplayValue { get; private set; }
        public V HiddenValue { get; private set; }
    
    
        public override string ToString()
        {
            return DisplayValue == null ? "" : DisplayValue.ToString();
        }
    }

    Then adding a `Create` function can make creating them easier due to type inference of methods:

    public static CheckBoxItem<K, V> Create<K, V>(K displayValue, V hiddenValue)
    {
        return new CheckBoxItem<K, V>(displayValue, hiddenValue);
    }

    To create the CheckedListBox could look something like this:

    var list = new List<CheckBoxItem<string, int>>();
    list.Add(Create("Checkedlistbox item 1", 5));
    list.Add(Create("Checkedlistbox item 2", 7));
    //... add the rest
    
    CheckedListBox box = new CheckedListBox();
    box.Items.AddRange(list.Cast<object>().ToArray());
    Controls.Add(box);

    Once you have all of that summing the underlying values of all of the checked items is pretty trivial:

    int sum = box.CheckedItems.Cast<CheckBoxItem<string, int>>()
        .Sum(item => item.HiddenValue);
    @Everyone else in the thread, is it really that hard to comprehend that he wants to display something other than the underlying value?  This is just like how the `select` HTML tag works; there is a separate property for the text and underlying value for each item, and they're only occasionally identical.  In this case you need to do a bit of work to get there, but the concept is still simple enough.


    • Edited by servy42 Thursday, November 8, 2012 3:08 PM
    • Proposed as answer by Jason Dot Wang Friday, November 9, 2012 7:37 AM
    • Marked as answer by Jason Dot Wang Friday, November 16, 2012 8:35 AM
    Thursday, November 8, 2012 3:06 PM
  • @Jason Wang, note that all of the answers you've proposed other than Viorel's and mine assume that the display value and the underlying value are the same; both an "int", and that's specifically NOT what the OP want's, so they don't answer the question.
    Friday, November 9, 2012 3:40 PM
  • Hello and many thanks.

    Please read my question carefully. I am working with a CHECKLISTBOX not checkbox! Where is all the code about checkbox coming from?????

    Saturday, November 10, 2012 11:03 PM
  • @Topa ... have you even tried @Servy's code? It should do what you're asking about ... his code uses a CheckedListBox (as do most of the replies in this thread).

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Sunday, November 11, 2012 1:34 AM
  • Hi Servy 42,

    Thanks. Did you try putting the code above in VS2005? Please do as there is so many errors that I am at cross roads on what to do.

    Looking forward to yours.

    Sunday, November 11, 2012 2:18 AM
  • Hello and many thanks.

    Please read my question carefully. I am working with a CHECKLISTBOX not checkbox! Where is all the code about checkbox coming from?????

    I find this funny, given that the answer you marked only deals with checkboxes, not a checked list box, and doesn't even solve the problem you mentioned in the OP.
    Monday, November 12, 2012 2:46 PM
  • Hi Servy 42,

    Thanks. Did you try putting the code above in VS2005? Please do as there is so many errors that I am at cross roads on what to do.

    Looking forward to yours.

    I used C# 3.0, not 2.0, which is why you were getting errors.

    The general approach is still the one that you should use, you just won't be able to use the LINQ functions there; you'll need to write them out yourself using a `foreach`.  It should be a simple enough transformation though.

    Monday, November 12, 2012 2:48 PM
  • i understand your problem..

    you can Compare the checkboxlistitems in the code by assigning  value with  same name...

    below is the Example in which i have calculated fees by just selecting the items of chckboxlist and given the same names to chckboxlist items as NET,JAVA,Csharp,PHP..

    i hope you'll get this...

     private void button_select_Click(object sender, EventArgs e)
            {
                int NET = 3500;
                int JAVA = 4000;
                int CSharp = 4500;
                int PHP = 3000;
                int totall = 0;
                listBox1.Items.Clear();
                listBox1.Items.Add(txt_name.Text);
                foreach(String s in checkedListBox1.CheckedItems)
                {
                    if(s=="NET")
                    {
                        listBox1.Items.Add(s+ "=" +NET);
                        totall = totall + NET;
                    }
                    if(s=="JAVA")
                    {
                        listBox1.Items.Add(s+ "=" +JAVA);
                        totall = totall + JAVA;
                    }
                    if(s=="CSharp")
                    {
                        listBox1.Items.Add(s+ "=" +CSharp);
                        totall = totall + CSharp;
                    }
                    if(s=="PHP")
                    {
                        listBox1.Items.Add(s+ "=" +PHP);
                        totall = totall + PHP;
                    }

                }listBox1.Items.Add("---------");
                listBox1.Items.Add(totall);

            }

                              
    Tuesday, March 14, 2017 4:12 PM