问题
First of I've searched allover, found the same problems, but with very different answers that i wasn't very fond of. To make it clear, I DON'T want the TextBox rebuild. So I'm taking a shot here.
I'm having this problem that I want my combobox like AutoCompleteMode.Suggest but with a "contains" search instead of "starts with". This is my code so far like I want except contains search:
string displayMember = "Kund";
string sqlString = "select Kund from [Blad1$] order by Kund";
con.Open();
DataRow dataRow = table.NewRow();
dataRow[displayMember] = "";
table.Rows.InsertAt(dataRow, 0);
cB1.DataSource = table;
cB1.DisplayMember = displayMember;
cB1.SelectedIndex = 0;
cB1.Text = "";
OleDbCommand cmd = new OleDbCommand(sqlString, con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read()) namesCollection.Add(dr[displayMember].ToString());
dr.Close();
con.Close();
cB1.AutoCompleteMode = AutoCompleteMode.Suggest;
cB1.AutoCompleteSource = AutoCompleteSource.CustomSource;
cB1.AutoCompleteCustomSource = namesCollection;
But here I have a code that doeas the search contains job by suggesting it in a dropdown, but it adds the top item to the current char in my inputbox. Like if I type "p", and it founds "Harry Potter", it looks like this "pHarry Potter". Also I can only type ONE char.
//join previous text and new pressed char
string name = string.Format("{0}{1}", cB1.Text, e.KeyChar.ToString());
DataRow[] rows = table.Select(string.Format("Kund LIKE '%{0}%'", name));
DataTable filteredTable = AllNames.Clone();
foreach (DataRow r in rows) filteredTable.ImportRow(r);
cB1.DataSource = null;
cB1.DataSource = filteredTable.DefaultView;
cB1.DisplayMember = "Kund";
cB1.DroppedDown = true;
I feel I'm so close, if I could somehow combine these two codes.I mean, the bottom code do find the rows I want, but doesn't act quiet like autocompletemode.suggest. EDIT: I've did some progress. Although not satisfactory yet, but on the right way. Still I dont want to use a textbox to type in. To use this method is ackward.
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection(@"some file.xls");
da = new OleDbDataAdapter("SELECT Kund FROM [Blad1$] ORDER BY Kund", con);
da.Fill(AllNames);
table = AllNames.Copy();
DataRow dataRow = table.NewRow();
dataRow["Kund"] = "";
table.Rows.InsertAt(dataRow, 0);
tempTable();
}
public void tempTable()
{
try
{
DataRow[] rows = table.Select("Kund LIKE '%" + textBox1.Text + "%' OR Kund LIKE ''");
DataTable filteredTable = AllNames.Clone();
foreach (DataRow r in rows) filteredTable.ImportRow(r);
cB1.DataSource = null;
cB1.DataSource = filteredTable.DefaultView;
cB1.DisplayMember = "Kund";
cB1.SelectedIndex = 0;
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
tempTable();
cB1.DroppedDown = true;
Please help me.
来源:https://stackoverflow.com/questions/19020313/combobox-autocompletemode-suggest-contain