2012-09-26 48 views
1

我在C#中的新種類,我的問題是如何將checked列表框中的選中項添加到列表框中,並且當我取消選中此項時,也將它從列表框中刪除.. !添加或刪除checkedlistbox列表框中的已檢查的項目

+0

什麼是你到目前爲止? –

+0

我正在使用foreach,在添加部分很好,但問題始於取消選中項目並從列表框中刪除。 –

回答

3

如果你有checkedListBox1checkedListBox和你listBoxlistBox1,你應該增加這個ItemCheck EventcheckedListBox

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

檢查checkedListBox的事件選項卡,ItemCheck事件應指向此方法 –

+0

這很好實施。 –

0

添加項目:

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

} 
+0

如何在這種情況下使用itemcheck事件? –

+0

您使用selectedItems爲了選擇 –

+0

我使用此代碼,但似乎調試器不執行項目檢查事件。 公共無效checkedListBox1_ItemCheck(對象發件人,ItemCheckEventArgs E) { 如果(e.NewValue == CheckState.Checked) { listBox1.Items.Add(checkedListBox1.SelectedItem.ToString()); } } 私人無效checkedListBox1_SelectedIndexChanged(對象發件人,EventArgs的) { listBox1.Text = checkedListBox1.SelectedItem.ToString(); } –

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