Combobox AutoCompleteMode建议包含

时间:2013-09-26 05:50:19

标签: c# contains

我第一次全身心地搜索,发现了同样的问题,但答案非常不同,我不是很喜欢。为了说清楚,我不希望TextBox重建。 所以我在这里拍摄。

我遇到了这个问题,我希望我的组合框像AutoCompleteMode.Suggest但是使用“包含”搜索而不是“以...开头”。到目前为止,这是我想要的代码,除了包含搜索:

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;

但是在这里我有一个代码,通过在下拉列表中建议搜索包含作业,但它将顶部项添加到我的输入框中的当前字符。就像我输入“p”,它发现“哈利波特”一样,它看起来像是“pHarry Potter”。此外,我只能键入一个字符。

//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;

我觉得我非常接近,如果我能以某种方式将这两个代码组合在一起。我的意思是,底部代码确实找到了我想要的行,但不像autocompletemode.suggest那样安静。 编辑:我已经取得了一些进展。虽然还不尽如人意,但是正确的方式。 我仍然不想使用文本框输入。使用此方法很麻烦。

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;

请帮帮我。

0 个答案:

没有答案