Winform如何使用SelectedValue从组合框中删除Item?

时间:2017-01-04 14:25:58

标签: c# winforms combobox

      public void Fill()
      {
        cmb1.DataSource = dt;
        cmb1.DisplayMember = "Name";
        cmb1.ValueMember = "ID";
      }

     public void Remove()//by Text
     {
            string selectedItem ="Jack";
            cmb1.Items.Remove(selectedItem );
     }

     public void Remove()//by Value
     {
            string selectedvalue ="10";
            cmb1.Items.RemoveAt(selectedvalue);

     }

本规范已使用但未奏效。 不使用值或Text.Or删除任何其他方法来填充没有DataSource的组合框。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

class Student {
        public int ID{get;set;}
        public string Name { get; set; }

        // You override this method depending in what you want to show on the comboBox as text
        public override string ToString()
        {
            return Name;
        }
    }

    private void fillComboBox(List<Student> students)
    {
        // We manually fill the comboBox Items; The displayed text is going to be define by the ToString() method this object has define
        students.ForEach(x => cmb1.Items.Add(students));
    }
    private void button1_Click(object sender, EventArgs e)
    {
        // We can remove the items by just doing this
        cmb1.Items.Remove(cmb1.SelectedItem);
    }

答案 1 :(得分:0)

您可以执行以下操作,因为您使用的是数据源:

DataTable dt = (DataTable)cmb1.DataSource;
dt.Rows.RemoveAt(cmb1.SelectedIndex);