We help IT Professionals succeed at work.

Multiple Checkbox value in a table field and how to sepearte the value and check the respective checkboxes (.NET 2, C#)

Dhanin asked
Last Modified: 2008-04-24
       I have a form (.NET 2, C#) and cusine types are in Checkboxes. This cusine type is a static one.
There are 10 cusine types (Thai, Western, Indian, Itally etc.,) all are displayed in checkbox for the user to select more than one cusine type.

Though it's static thing, I would like to store this info in a single field in table. How do I store this info (concatenate when the user submits), then how to display it. i.e seperate string and check the respective checkboxes (cusine type) in the edit mode.

Could anyone help me how to retrieve and concatenate before updating to table field and also when retreval from a field how to seperate and select the respective checkbox.

Thank you.
Watch Question

Not pretty, but it should work.  Maybe someone else has a better solution.

using System.Text;

StringBuilder sb = new StringBuilder;

if (chkThai.Checked == true)

if (chkWestern.Checked == true)

// Save this string in the table
string values = sb.ToString();

// Then when you want to retrieve the values:

if (values.Substring(0, 1) == "1")
    chkThai.Checked = true;
    chkThai.Checked = false;

if (values.Substring(1, 1) == "1")
    chkWestern.Checked = true;
    chkWestern.Checked = false;
One other note:  I did it the way I did it above because you asked how to store the values as a string.  A more efficient way to store a set of values this way would be as a bitmask using the BitVector32 structure.  You can then store the data from all the check boxes on the form in a 32-bit integer, instead of a 10-byte string.  Let me knowif you're interested and I'll post an example.
Dirk HaestProject manager

--> concatenate the selected fields into 1 string with a specified delimiter.
        private void button3_Click(object sender, EventArgs e)
            StringBuilder s = new StringBuilder();
            if (checkedListBox1.CheckedItems.Count != 0)
                // If so, loop through all checked items and print results.
                for (int x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++)
                    s.Append (checkedListBox1.CheckedItems[x].ToString() + ";");
                s.Length = s.Length - 1;

--> Select the items in the listbox, depending of the value in the database
        private void button4_Click(object sender, EventArgs e)
            string strFromDb ="English;Fastfood";

            char[] splitter = { ';' };

            string[] arSelected = strFromDb.Split(splitter);

            for (int x = 0; x < arSelected.Length; x++)
                for (int i = 0; i <= checkedListBox1.Items.Count - 1; i++)
                    if (arSelected[x].ToString() == checkedListBox1.Items[i].ToString())
                        checkedListBox1.SetItemChecked(i, true);



u may record the checkbox values into hidden value, the read it from code behind
<form id="form1" runat="Server" onsubmit="recordValue();" method="post">
<div id="chk">
<input type="checkbox" id="chk1" value="test1" />
<input type="checkbox" id="chk2" value="test2" />
<input type="checkbox" id="chk3" value="test3" />
<input type="checkbox" id="chk4" value="test4" />
<input type="hidden" id="hid1" runat="server" />

function recordValue()
    objDiv = document.getElementById("chk");
    objChks = objDiv.getElementsByTagName("INPUT");
    objHid = document.getElementById("hid1");
    for (i=0; i < objChks.length; i++)
         if (objChks[i].type == "checkbox")
                 if (objChks[i].checked)
                       objHid.value += objChks[i].value + ",";

from your code behind
.......void button1_click(..............)
string strValues = Hidden1.value;

it's just a quick idea for recording the values, HTH :o)
OK, there are 2 ways to do this, one is simple but expensive, the other is not that simple but economic.
1- Do it using Integers where you can AND and OR them to get what you want. I am talking about binary bitwise AND and OR. How this goes:
Use CheckBoxList for this and set the values for the items to the appropriate integers. For example:
first item in the list of checkboxes has the value 1, second 2, third 4, fourth 8, 16, 32, ... and so on. This is Binary of 00000001, 00000010, 00000100, 00001000, ... and so on.
How this helps is by ORing them, so if you selected both the first and the second the result will be 00000001 | 00000010 = 00000011, the syntax for this is:
int item1 = 1;
int item2 = 2;
int orResult = item1 | item2;

now this gives us 1 integer holding all the selections.
to know IF a checkbox is selected we can do this:
for example if we want to know if the third checkbox is checked :
if((orResult & 00000100) != 0)
//do something
When we use the & operator which is binary &, we can check if the third 00000100 checkbox is selected by anding that value with the resulting number (that we will get from the Database).

2 - The second more expensive way is to concatenate strings:
checkbox1 has a value = 'Thai', checkbox2 has value 'French' concatenation is something like:
"Thai" + "|" + "French" = "Thai|French"
to separate them we can split them into a string array:
string[] aSelections = sConcatenated.Split("|");
for loop on the array and we are done.

Is it a checked ListBox or individual CheckBoxes on the form?
CheckBoxList Control lets you specify the value for each ListItem.
Right, but I got the impression it was individual CheckBoxes, which makes iterating through them a little more complicated.  If it's a CheckedListBox, you can iterate the ListBox's Items collection.  If they are inidividual CheckBoxes, you need to get each one by name.
It is easier to use the CheckBoxList unless you have some javascrpt to bind to each individual checkbox.
OK, I'll pile on.  Here's how you would do this using a BitVector32 to create a singe 32-bit integer with all your values.

using System.Collections.Specialized;

            BitVector32 bv = new BitVector32(0);
            int thai = BitVector32.CreateMask();
            int western = BitVector32.CreateMask(thai);
            int indian = BitVector32.CreateMask(indian);
            int italian = BitVector32.CreateMask(italian);

            bv[thai] = chkThai.Checked;
            bv[western] = chkWestern.Checked;
            bv[indian] = chkIndian.Checked;
            bv[italian] = chkItalian.Checked;

            // This is the integer you would save to the table
            int cuisineData = bv.Data;

            // Then when you want to retrieve the values:
            int thai = BitVector32.CreateMask();
            int western = BitVector32.CreateMask(thai);
            int indian = BitVector32.CreateMask(indian);
            int italian = BitVector32.CreateMask(italian);

            // cuisineData is the integer you retrieved from the database
            BitVector32 bv = new BitVector32(cuisineData);

            chkThai.Checked = (bool)bv[thai];
            chkWestern.Checked = (bool)bv[western];
            chkIndian.Checked = (bool)bv[indian];
            chkItalian.Checked = (bool)bv[italian];
This one is on us!
(Get your first solution completely free - no credit card required)

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.