【发布时间】:2012-07-19 07:52:11
【问题描述】:
我有一个带有Foo 类型对象的组合框,这里是Foo 类:
public class Foo
{
public string name { get; set; }
public string path { get; set; }
}
Foo.name 是组合框中显示的文本,Foo.path 是所选选项的值。
我想在完成一些操作后从组合框中删除一个选项。
我试过这些方法:
-
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);
没有什么对我有用。 : / 如何做到这一点?
更新
这就是我初始化组合框的方式:
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";
【问题讨论】:
-
您是在放入对象吧?那么你为什么要删除 .Text 和 .ToString() 呢?尝试使用 Items.Find (of FindExact) 找到正确的对象并尝试删除其结果。伪:comboBox2.Items.Remove(comboBox2.Items.Find(fooItem.Text));
-
这里的另一件事是您如何填充组合框?如果您是 dataBinding,那么请尝试从底层源而不是从组合中删除该项目...
-
@Gerald Versluis 我尝试通过以下方式做到这一点:
comboBox2.Items.RemoveAt(comboBox2.Items.IndexOf(comboBox2.Text));和comboBox2.Items.RemoveAt(comboBox2.Items.IndexOf(comboBox2.SelectedValue));- 每次我看到一个错误.. -
System.ArgumentException: Items collection cannot be modified when the DataSource property is set.- 与我的删除命令一致 -
这就是我问“你如何填充你的 ComboBox”的原因。您将需要从 DataSource 中删除该项目并重新绑定 ComboBox,直接从组合中删除将不起作用...