How to delete object from combobox?

前端 未结 6 1954
遇见更好的自我
遇见更好的自我 2021-01-25 18:37

I have a combobox with objects of Foo type, here is the Foo class:

public class Foo
{
    public string name { get; set; }
    public s         


        
相关标签:
6条回答
  • 2021-01-25 18:44

    Use ComboBox.SelectedIndex property.

    For example: let me have comboBox1 added to the form. In the delete button:

    if (comboBox1.SelectedIndex >= 0)
        comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
    
    0 讨论(0)
  • 2021-01-25 18:48
    combox1.Remove(takes an object)
    Object selectedItem = comboBox1.SelectedItem;
    

    So you cna do it this way combox1.Remove(selectedItem);

    0 讨论(0)
  • 2021-01-25 18:49

    Suppose you want to Remove Items by Index:

        combo2data.RemoveAt(0); //Removing by Index from the dataSource which is a List
    
        //Rebind
        comboBox2.DataSource = null;
        comboBox2.DataSource = combo2data;  
        comboBox2.ValueMember = "path";  
        comboBox2.DisplayMember = "name";  
    

    Suppose you want to Remove by seraching for a member value

        Foo item = combo2data.Where(f => f.name.Equals("Tom")).FirstOrDefault();
        if (item != null)
        {
            combo2data.Remove(item);
            comboBox2.DataSource = null;
            comboBox2.DataSource = combo2data;  
            comboBox2.ValueMember = "path";  
            comboBox2.DisplayMember = "name";  
        }
    
    0 讨论(0)
  • 2021-01-25 18:49

    These 2 commands will remove an item from your data source.

    list.Remove((Foo)comboBox1.SelectedItem);
    

    or

    list.Remove(list.Find(P=>P.name == comboBox1.SelectedText));
    
    0 讨论(0)
  • 2021-01-25 19:00

    I think the secret is to first attribute null to the datasource and after rebind to a modified collection:

    int idToRemove = 1;
    var items = (cbx.DataSource as List<MyEntity>);
    items.RemoveAll(v => v.Id == idToRemove);
    rebindCombobox(cbx, items, "Name", "Id");
    
    
    private void rebindCombobox(ComboBox cbx, IEnumerable<Object> items, String displayMember, String valueMember)
    {
        cbx.DataSource = null;
        cbx.DisplayMember = displayMember;
        cbx.ValueMember = valueMember;
        cbx.DataSource = items;
    }
    
    0 讨论(0)
  • 2021-01-25 19:01

    comboBox2.Items.Remove(comboBox2.SelectedValue); will only remove from the combobox, not from the datasource bound to the combobox. You may remove it from the datasource and re-bind the datasource.

    0 讨论(0)
提交回复
热议问题