C# CheckBox List Selected Items.Text to Labels.Text

brmcdani44 picture brmcdani44 · May 19, 2011 · Viewed 28.2k times · Source

I have a CheckBoxList and 5 labels.

I would like the text value of these Labels to be set to the 5 selections made from the CheckBoxList after the user clicks on a button. How would I get this accomplished?

Thanks in advance.

Answer

Caspar Kleijne picture Caspar Kleijne · May 19, 2011
  • bind an event to a button,
  • iterate trough the Items property of the CheckBoxList
  • set the text value according to the selected property of the listitem

like:

protected void button_Click(object sender, EventArgs e)
{
    foreach (ListItem item in theCheckBoxList.Items)
    {
        item.Text = item.Selected ? "Checked" : "UnChecked";
    }
}

to add a value you could do:

 foreach (ListItem item in theCheckBoxList.Items)
 {
        item.Text = item.Selected ? item.Value  : "";
 }

or display al values in a mini-report:

    string test = "you've selected :";
    foreach (ListItem item in theCheckBoxList.Items)
    {
        test += item.Selected ? item.Value + ", " : "";
    }
    labelResult.Text = test;