从ComboBox 1中删除从ComboBox 1中选择的项目

时间:2013-08-01 03:02:31

标签: c# winforms combobox

我有两个组合框从同一个List中获取数据包含一个对象。 如何从ComboBox 2中的项目中删除ComboBox 1中的选定项目?

comboBox1.DataSource = CityList;    //CityList is list contain objects
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";

comboBox2.DataSource = CityList;
comboBox2.ValueMember = "ID";
comboBox2.DisplayMember = "Name";
comboBoxTargetState.Items.Remove(comboBoxCurrentState.SelectedItem); // give me an excption

1 个答案:

答案 0 :(得分:1)

使用DataSource时,您必须从源Items中删除该项(因为当ComboBox是数据绑定时它是只读的):

if(comboBoxCurrentState.SelectedIndex > -1)
  CityList.RemoveAt(comboBoxCurrentState.SelectedIndex);