user3722956
user3722956

Reputation: 59

c# combobox autocomplete set display text and value

I need to create a combobox autocomplete which display text Name but when I click on text it gets value "ID" binding with "Name". I have already created a code but it is not working and I'm so confusing with set display text and value into combobox and autocomplete data-source binding.

private void loadAutoCompleteValues()
{
    autoCompleteCombo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    autoCompleteCombo.AutoCompleteSource = AutoCompleteSource.CustomSource;

    DataTable products;
    con.MysqlQuery("select * from products");
    products = con.QueryEx();
    Dictionary<string, string> comboSource = new Dictionary<string, string>();

    for (int i = 0; i < products.Rows.Count; i++)
    {
        DataRow dr = products.Rows[i];
        comboSource.Add(dr["id"].ToString(), dr["name"].ToString());
    }

    autoCompleteCombo.DataSource = new BindingSource(comboSource, null);
    autoCompleteCombo.DisplayMember = "Value";
    autoCompleteCombo.ValueMember = "Key";
}

private void autoCompleteCombo_SelectedIndexChanged(object sender, EventArgs e)
{
    string key = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Key;
    string value = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Value;

    MessageBox.Show(key + "   " + value);
} 

Upvotes: 1

Views: 1883

Answers (1)

JohnG
JohnG

Reputation: 9479

I may be incorrect here, however using your code I simply added the line autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; to your code and it worked as expected.

  autoCompleateCombo.DataSource = new BindingSource(comboSource, null);
  autoCompleateCombo.DisplayMember = "Value";
  autoCompleateCombo.ValueMember = "Key";
  autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; //<-- Added this line

Upvotes: 1

Related Questions