[英]AutoComplete ComboBox C#
我正在將巨大的數據庫從excel(約2000項)加載到組合框。 例如CD標題。 然后,我從2000年中選擇1張CD標題。我想在這里使用自動完成功能,但我不知道如何。
// 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);
}
在表單上,您需要為ComboBox設置兩個屬性:
AutoCompleteMode應該為“ Suggest”,“ Append”或“ SuggestAppend”。 我建議SuggestAppend。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.