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

2019-04-13 16:59发布

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.

4条回答
聊天终结者
2楼-- · 2019-04-13 17:07

Why don't you have one label and on the button click do something like:

foreach (var li in CheckList1.Items)
{
   if(li.Checked)
      Label1.Text = li.Value + "<br />";
}

That may not be the exact syntax but something along those lines.

查看更多
混吃等死
3楼-- · 2019-04-13 17:12

find selected items from CheckboxList by Lambda Linq:

var x = chkList.Items.Cast<ListItem>().Where(i => i.Selected);
    if (x!=null && x.Count()>0)
    {
         List<ListItem> lstSelectedItems = x.ToList();            
         //... Other ...
    }
查看更多
贪生不怕死
4楼-- · 2019-04-13 17:20
  • 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;
查看更多
Animai°情兽
5楼-- · 2019-04-13 17:28

Use this in LINQ:

foreach (var cbx3 in CheckBoxList2.Controls.OfType<CheckBox>().Where(cbx3 => cbx3.ID == s))
{
    cbx3.Checked = true;
}
查看更多
登录 后发表回答