Search code examples
c#winformscombobox

How to delete object from combobox?


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

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

The Foo.name is the displayed text in the combobox and Foo.path is the value of the selected option.

I want to delete an option from the combobox after some operation I made.

I've tried these ways:

  • 1

    comboBox2.Items.Remove(@comboBox2.Text);  
    
  • 2

    comboBox2.Items.Remove(@comboBox2.SelectedValue.ToString());  
    
  • 3

    Foo ToDelete = new Foo();
    ToDelete.name = @comboBox2.Text;
    ToDelete.path = @comboBox2.SelectedValue.ToString();
    comboBox2.Items.Remove(ToDelete); 
    

Nothing works for me. : / How to do this?

UPDATE

This is how I'm initializing my combobox:

    string[] filePaths = Directory.GetFiles(sites.paths[comboBox1.SelectedIndex]);

        List<Foo> combo2data = new List<Foo>();

        foreach (string s in filePaths)
        {
            Foo fileInsert = new Foo();
            fileInsert.path = s;
            fileInsert.name = Path.GetFileName(s);
            combo2data.Add(fileInsert);
        }

        comboBox2.DataSource = combo2data;
        comboBox2.ValueMember = "path";
        comboBox2.DisplayMember = "name";

Solution

  • 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.