【问题标题】:remove an item from combobox从组合框中删除项目
【发布时间】:2014-06-17 04:48:49
【问题描述】:

我想从我的 D: 驱动器中的文本文件中的所有 4 个字母单词中绑定一个组合框,所以我编写了一个类并声明了一个名称和值:

public class Words
{
    public string Name { get; set; }
    public string Value { get; set; }
}

在我的表单中,使用此代码将所有 4 个字母绑定到我的组合框:

string fileLoc = @"d:\Words.txt";
string AllWords = "";
var word4 = new List<Words>();
if (File.Exists(fileLoc))
{
    using (TextReader tr = new StreamReader(fileLoc))
    {
        AllWords = tr.ReadLine();
    }
}
string[] words = AllWords.Split('-');
foreach (string word in words)
{
     if (word.Length == 4)
     {
        word4.Add(new Words() { Name = word, Value = word });
     }
}
this.comboBox4.DataSource = word4;
this.comboBox4.DisplayMember = "Name";
this.comboBox4.ValueMember = "Value";
this.comboBox4.DropDownStyle = ComboBoxStyle.DropDownList;

现在,我想在选择它并单击按钮时删除单词。只是从组合框中删除而不是从文本文件中删除。重新加载表单后,所有单词必须再次显示在组合中。 因为我对所有长度的单词使用了许多组合,并且在不同的条件下,只有一个组合显示给用户,用于访问和删除我编写此方法的项目:

 ComboBox combo = this.Controls.OfType<ComboBox>().First(K => K.Visible);
 combo.Items.Remove(combo.SelectedIndex);

但它不会删除任何项目。请帮助我。

【问题讨论】:

    标签: c# wpf winforms combobox


    【解决方案1】:

    当您设置数据源时,您可能无法修改项目集合。您需要从数据源中删除选定的项目并重新绑定它。

    if (comboBox1.SelectedIndex != -1)
    {
        var words = comboBox1.DataSource as List<Word>;
        words.Remove(comboBox1.SelectedItem as Word);
        comboBox1.DataSource = null;
        comboBox1.DataSource = words;
        this.comboBox1.DisplayMember = "Name";
        this.comboBox1.ValueMember = "Value";
        this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多