【问题标题】:Add or remove checked items from checkedlistbox to listbox将选中的项目从选中列表框中添加或删除到列表框
【发布时间】:2012-09-26 17:57:29
【问题描述】:

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

【问题讨论】:

  • 到目前为止你有什么?
  • 我使用的是 foreach,在添加部分效果很好,但问题开始于取消选中该项目并从列表框中删除。

标签: c# checkedlistbox


【解决方案1】:

如果您有 checkedListBox1 作为 checkedListBox 并且您的 listBox 称为 listBox1,您应该为您的 checkedListBox 添加此 ItemCheck Event

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]);
}

【讨论】:

  • checkedListBox的事件标签,ItemCheck事件应该指向这个方法
【解决方案2】:

添加项目:

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);

}

【讨论】:

  • 在这种情况下如何使用 itemcheck 事件?
  • 你使用 selectedItems 来选择
  • 我正在使用这段代码,但调试器似乎没有执行项目检查事件。 public void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { if (e.NewValue == CheckState.Checked) { listBox1.Items.Add(checkedListBox1.SelectedItem.ToString()); } } 私人无效checkedListBox1_SelectedIndexChanged(对象发送者,EventArgs e){ listBox1.Text = checkedListBox1.SelectedItem.ToString(); }
  • 我在 chekedlistbox1_itemcheck 事件中使用了一个断点,但它似乎没有被调试器击中。
  • 检查您是否添加了代表
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多