C# 从组合框中删除项目
我想从我的D:drive中的文本文件中的所有4个字母和单词绑定一个组合框,因此我编写了一个类并声明了一个名称和值:C# 从组合框中删除项目,c#,wpf,winforms,combobox,C#,Wpf,Winforms,Combobox,我想从我的D:drive中的文本文件中的所有4个字母和单词绑定一个组合框,因此我编写了一个类并声明了一个名称和值: public class Words { public string Name { get; set; } public string Value { get; set; } } 在我的表单中,使用以下代码将所有4个字母绑定到我的组合框: string fileLoc = @"d:\Words.txt"; string AllWords = ""; var wor
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;
stringfileloc=@“d:\Words.txt”;
字符串AllWords=“”;
var word4=新列表();
if(File.Exists(fileLoc))
{
使用(TextReader tr=新的StreamReader(fileLoc))
{
AllWords=tr.ReadLine();
}
}
string[]words=AllWords.Split('-');
foreach(单词中的字符串)
{
if(word.Length==4)
{
添加(新词(){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);
ComboBox combo=this.Controls.OfType().First(K=>K.Visible);
combo.Items.Remove(combo.SelectedIndex);
但它不会删除任何项目。请帮助我。在设置数据源时,您可能无法修改项目集合。您需要从数据源中删除选定项并重新绑定它
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;
}
if(comboBox1.SelectedIndex!=-1)
{
var words=comboBox1.DataSource作为列表;
words.Remove(组合框1.SelectedItem作为Word);
comboBox1.DataSource=null;
comboBox1.DataSource=单词;
this.comboBox1.DisplayMember=“Name”;
this.comboBox1.ValueMember=“Value”;
this.comboBox1.DropDownStyle=ComboBoxStyle.DropDownList;
}