1

首先,我进行了全面搜索,发现了相同的问题,但答案却截然不同,我不是很喜欢。为了清楚起见,我不想重建 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 那样安静。 编辑:我已经取得了一些进展。虽然还不能令人满意,但在正确的道路上。我仍然不想使用文本框输入。使用这种方法是 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;

请帮我。

4

0 回答 0