i'm loading huge database from excel (about 2000 items) to combobox. For example CD titles. Then i select 1 CD title from this 2000. I'd like to use here autocomplete, but i don't know how..
// 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);
}
On your form, you need to set two properties for your ComboBox:
AutoCompleteMode should be Suggest, Append, or SuggestAppend. I recommend SuggestAppend.
AutoCompleteSource should be ListItems.
this method does it for you
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
{
}
}
and implement "GetColumnData_FromDB" as you wish
In addition to setting the property referenced by John about 10 minutes ago, here is some code that I use to databind my combo box:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With