c#combobox autocomplete设置显示文本和值

时间:2017-01-20 04:11:57

标签: c# combobox autocomplete

我需要创建一个显示text Name的组合框自动完成功能,但是当我点击text时,它会获得value" ID&# 34;绑定"名称"。我已经创建了一个代码,但它无法运行,我对set display textvalue混淆了组合框和自动完成data-source绑定。

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);
} 

1 个答案:

答案 0 :(得分:1)

我在这里可能不正确,但是使用您的代码我只是将代码行autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems;添加到您的代码中,它按预期工作。

  autoCompleateCombo.DataSource = new BindingSource(comboSource, null);
  autoCompleateCombo.DisplayMember = "Value";
  autoCompleateCombo.ValueMember = "Key";
  autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; //<-- Added this line
寻找你感兴趣的贴纸↓↓↓
豫ICP备18024241号-1