如何从组合框中删除对象? [英] How to delete object from combobox?
问题描述
我有一个组合框,其中包含 Foo
类型的对象,这是 Foo
类:
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; }
}
Foo.name
是组合框中显示的文本, Foo.path
是所选选项的值。
The Foo.name
is the displayed text in the combobox and Foo.path
is the value of the selected option.
I想要在执行一些操作后从组合框中删除一个选项。
I want to delete an option from the combobox after some operation I made.
我尝试了以下方式:
-
1
1
comboBox2.Items.Remove(@comboBox2.Text);
2
2
comboBox2.Items.Remove(@comboBox2.SelectedValue.ToString());
3
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?
更新
这就是我的方法m初始化组合框:
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";
推荐答案
comboBox2.Items.Remove(comboBox2.SelectedValue);只会从组合框中删除,而不会从绑定到组合框中的数据源中删除。您可以将其从数据源中删除,然后重新绑定该数据源。
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.
这篇关于如何从组合框中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!