Click here to Skip to main content
16,016,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<pre lang="c#">
cmbSourceTag1.DataSource = new BindingSource(objSource, null);
cmbSourceTag1.DisplayMember = "Value";
cmbSourceTag1.ValueMember = "Key";


how to remove and add new items to combobox ?
where objSource is
Dictionary<int, string>


What I have tried:

cmbSourceTag2.Items.RemoveAt(((KeyValuePair<int, string>)cmbSourceTag2.Items[2]).Key);

it will throw the error
anyone have an idea to remove and add item from combobox?

Thanks
Posted
Updated 18-Jul-17 1:27am
Comments
Richard MacCutchan 18-Jul-17 4:15am    
You must remove/add items in the Datasource, not the combo.
nirmalVaishnav 18-Jul-17 4:31am    
but i want to remove from combobox..
have any idea about this?
Richard MacCutchan 18-Jul-17 10:43am    
Yes, do what I said.

1 solution

A combobox can use either an Items collection or a DataSource. They are mutually exclusive and the Items collection cannot be modified when a DataSource is used.

As Richard has said you must add and remove items from the datasource.

In choosing a Dictionary as the original datasource you have made this task quite complicated. A dictionary will not bind to a combobox directly as it does not implement the required IList interface. The BindingSource actually creates an intermediate System.ComponentModel.BindingList (populated with KeyValuePairs from dictionary) and then assigns that to the ComboBox.DataSource. In effect the dictionary is not bound to the combobox at all.

Lets assume there is a button which removes the selected item from the combobox. This is the code for it's click handler
C#
private void RemoveFromDictionary_Click(Object sender, EventArgs e) {
  if (cbx.SelectedIndex != -1) {
    KeyValuePair<int, string> item = (KeyValuePair<int, string>)cbx.SelectedItem;
    // Remove from dictionary
    dic.Remove(item.Key);
    // Force the BindingSource to recreate the intermediate BindingList
    // and refresh the combobox
    cbxBindingSource.DataSource = null;
    cbxBindingSource.DataSource = dic;
  }
}

If you can redesign your program to use a BindingList directly instead of the dictionary, the code will become much simpler.
C#
 private void RemoveFromList_Click(Object sender, EventArgs e) {
  if (cbx.SelectedIndex != -1) {
    bindlist.RemoveAt(cbx.SelectedIndex);
  }
}

Alan.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900