Когда вы запускаете этот код:
foreach(string item in combobox1.Items)
{
}
Коллекция элементов в выпадающем списке не может быть изменена. Поэтому, когда вы пытаетесь редактировать такие элементы, как это:
foreach(string item in combobox1.Items)
{
combobox1.Items.Add(item);
// or
combobox1.Items.Remove(item);
}
Это вызывает ошибку во время выполнения. Таким образом, реальные коллекции предметов должны храниться где-то еще за пределами выпадающего списка. Ниже одно из разрешений.
public partial class Form1 : Form
{
Timer timer1 = new Timer();
List<string> lst = new List<string>();
public Form1()
{
InitializeComponent();
timer1.Interval = 1500;
timer1.Tick += Timer1_Tick;
lst.Add("Red");
lst.Add("Yellow");
lst.Add("Blue");
}
void RefreshComboBox()
{
comboBox1.Items.Clear();
if (textBox1.Text != null && textBox1.Text.Trim().Length > 0)
{
string txt = textBox1.Text.Trim().ToLower();
foreach (var str in lst)
{
if (str.ToLower().Contains(txt))
{
comboBox1.Items.Add(str);
}
}
}
else
{
foreach (var str in lst)
{
comboBox1.Items.Add(str);
}
}
}
private void Timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
RefreshComboBox();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
timer1.Stop();
timer1.Start();
}
}