Reputation: 109
I want binding a combobox from all 4 letters words in a text file in my D: drive, so I wrote a class and declare a name and value :
public class Words
{
public string Name { get; set; }
public string Value { get; set; }
}
In my form use this codes to bind all 4 letters to my combobox:
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;
now, I want remove word when select it and click a button.just remove from combobox not remove from text file.after reload the form must all words show on combo again. becuase I use many combo for all length of words,and in diffrent condition just one of combos are shown to user,for access and remove the item I wrote this method:
ComboBox combo = this.Controls.OfType<ComboBox>().First(K => K.Visible);
combo.Items.Remove(combo.SelectedIndex);
but it isn't remove any item.please help me.
Upvotes: 1
Views: 4692
Reputation: 19618
As you are setting the DataSource you may not able to modify the items collection. You need to remove the selected item from the Data Source and re bind it.
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;
}
Upvotes: 1