AutoComplete ComboBox C#

本文关键字:ComboBox AutoComplete | 更新日期: 2023-09-27 17:49:18

我正在加载巨大的数据库从excel(约2000项)到组合框。例如CD标题。然后我选择1 CD标题从这2000。我想使用这里的自动完成,但我不知道如何…

       // Loading items from Excel
       for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt < 2; cCnt++)
                {
                  str = Convert.ToString(saRet[rCnt,cCnt]);
                  // Loading items to ComboBox
                  ReferenceCombo.Items.Add(str);
            }

AutoComplete ComboBox C#

在表单中,您需要为ComboBox设置两个属性:

AutoCompleteMode应该是建议,追加,或建议追加。我推荐建议追加。

AutoCompleteSource应该是ListItems

这个方法为您做了

    private void LoadStuffNames()
    {
        try
        {
                string Query = "select stuff_name from dbo.stuff";
                string[] names = GetColumnData_FromDB(Query);
                comboName.AutoCompleteMode = AutoCompleteMode.Suggest;
                comboName.AutoCompleteSource = AutoCompleteSource.CustomSource;
                AutoCompleteStringCollection x = new AutoCompleteStringCollection();
                if (names != null && names.Length > 0)
                    foreach (string s in names)
                        x.Add(s);
                comboName.AutoCompleteCustomSource = x;
        }
        catch (Exception ex)
        {
        }
        finally
        {
        }
    }

和实现"GetColumnData_FromDB"如您所愿

除了设置大约10分钟前John引用的属性之外,这里是我用来绑定我的组合框的一些代码:

static BindingSource jp2bindingSource = new BindingSource();
void jp2FillCombo() {
  ComboBox comboBox1 = new ComboBox();
  comboBox1.Items.Clear();
  object[] objs = jp2Databind(new DataSet(), "Table1", "Column1", true);
  comboBox1.Items.AddRange(objs);
}
static object[] jp2Databind(DataSet dataset, string tableName, string columnName, bool unique) {
  jp2bindingSource.DataSource = dataset;
  jp2bindingSource.DataMember = tableName;
  List<string> itemTypes = new List<string>();
  foreach (DataRow r in dataset.Tables[tableName].Rows) {
    try {
      object typ = r[columnName];
      if ((typ != null) && (typ != DBNull.Value)) {
        string strTyp = typ.ToString().Trim();
        if (!String.IsNullOrEmpty(strTyp)) {
          if (unique) {
            if (!itemTypes.Contains(strTyp)) {
              itemTypes.Add(strTyp);
            }
          } else {
            itemTypes.Add(strTyp);
          }
        }
      }
    } catch (Exception err) {
      Global.LogError("Databind", err);
    }
  }
  try {
    itemTypes.Sort();
  } catch (Exception err) {
    Console.WriteLine(err.Message);
  }
  return itemTypes.ToArray();
}