Israel

Israel

  • 700
  • 1.3k
  • 217.6k

To find a piece of word anywhere in combobox

Aug 25 2018 7:13 PM
Hi,
 
I need to found any piece of word anywhere in combobox.
These code its works perfectly only with some itens added manually into my combobox:
private void cbx_TextChanged(object sender, EventArgs e)
{
if (cbx.Text.Length == 0) comboKeyPressed();
}
private void comboKeyPressed()
{
cbx.DroppedDown = true;
object[] originalList = (object[])cbx.Tag;
if (originalList == null)
{
originalList = new object[cbx.Items.Count];
 cbx.Items.CopyTo(originalList, 0);
 cbx.Tag = originalList;
 }
 string s = txtRubrica.Text.ToLower();
 IEnumerable newList = originalList;
 if (s.Length > 0)
 {
 newList = originalList.Where(item => item.ToString().ToLower().Contains(s));
}
 while (cbx.Items.Count > 0)
 {
cbx.Items.RemoveAt(0);
 }
 cbx.Items.AddRange(newList.ToArray());
}
private void cbx_KeyPress(object sender, KeyPressEventArgs e)
{
comboKeyPressed();
}
 
Now when I write these codes to populate in the same combobox datas from database to find any piece of word. Its crashs. 
conn.Open();
comm = new SqlCommand("SELECT DISTINCT name FROM Account", conn);
SqlDataReader sdr = comm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
cbx.DisplayMember = "name";
cbx.DroppedDown = true;
List list = new List();
foreach (DataRow row in dt.Rows)
{
list.Add(row.Field("name"));
}
this.cbx.Items.AddRange(list.ToArray());
cbx.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cbx.AutoCompleteSource = AutoCompleteSource.ListItems;
conn.Close();
///////////////////////doesnt allow repeat item in combobox////////////
for (int i = 0; i < cbx.Items.Count; i++)
{
for (int y = 0; y < cbx.Items.Count; y++)
{
if (y != i && cbx.Items[i].ToString() == cbx.Items[y].ToString())
{
cbx.Items.RemoveAt(i);
break;
}
}
}
 
There is any solution please??? 

Answers (6)