在checkedlistbox中添加或删除选中的项目到列表框

时间:2012-09-26 17:57:29

标签: c# checkedlistbox

我是C#的新手,我的问题是如何将已检查的项目从checkedlistbox添加到列表框中,当我取消选中此项目时,也将其从列表框中删除.. 谢谢!

3 个答案:

答案 0 :(得分:3)

如果checkedListBox1checkedListBoxlistBoxlistBox1,则应为ItemCheck Event checkedListBox >

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
  if (e.NewValue == CheckState.Checked)
    listBox1.Items.Add(checkedListBox1.Items[checkedListBox1.SelectedIndex]);
  if (e.NewValue == CheckState.Unchecked)
    listBox1.Items.Remove(checkedListBox1.Items[checkedListBox1.SelectedIndex]);
}

答案 1 :(得分:1)

添加项目:

YourListbox.Items.Add("");

链接:http://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.objectcollection.add.aspx

删除项目:

YourListbox.Items.Remove("");

链接:http://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.objectcollection.remove.aspx

var items = new System.Collections.ArrayList(listboxFiles.SelectedItems);

foreach (var item in items) {
        listbox.Items.remove(item);

}

答案 2 :(得分:0)

ASPX

<asp:CheckBoxList ID="_CheckBoxList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="CheckBoxList_SelectedIndexChanged">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:CheckBoxList>
<asp:ListBox ID="_ListBox" runat="server"></asp:ListBox>

CS

protected void CheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
{
    CheckBoxList cbx = (CheckBoxList)sender;

    _ListBox.Items.Clear();
    foreach (ListItem item in cbx.Items)
    {
        if(item.Selected)
            _ListBox.Items.Add(new ListItem(item.Text, item.Value));
    }

}

将其包装在更新面板中以使用AJAX