使用 C# windows 形式的文本搜索过滤组合框项目

Filtering combo box items using text search in C# windows form

我正在尝试在项目的所有字符中使用其文本属性来过滤组合框,而不仅仅是它们的开头。我在我的组合框的 TextChanged 事件中尝试下面的代码。但不幸的是,组合框在输入任意键后重置:

    private void cmbCompany_TextChanged(object sender, EventArgs e)
    {
        string QueryCompany = string.Format("select id,title from acc.dl where title LIKE '%" + cmbCompany.Text + "%' union select null , null order by title");
        SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
        DataTable DT1 = new DataTable();
        DA1.Fill(DT1);
        cmbCompany.DisplayMember = "Title";
        cmbCompany.ValueMember = "id";
        cmbCompany.DataSource = DT1;
    }

连接字符串 "con" 已定义并打开。 感谢您的帮助。

您可以在表单中添加一个文本框并使用它的文本进行过滤:

            string QueryCompany =
                string.Format(
                    "select id,title from acc.dl where dltype in (2,4)  union select null , null order by title");
            SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
            con.Open();
            DataTable DT1 = new DataTable();
            DA1.Fill(DT1);
            con.Close();
            DataView dv1 = new DataView(DT1);
            dv1.RowFilter = "Title like '%" + txtCompany.Text + "%' or Title is null";
            cmbCompany.DisplayMember = "Title";
            cmbCompany.ValueMember = "id";
            cmbCompany.DataSource = dv1;

并在选定的索引更改事件中:

txtCompany.Text = cmbCompany.Text;

下面是对我有用的代码部分,其中搜索部分不仅在开头而且在中间都有效。我还粘贴了额外的部分,负责在您按下回车按钮后将焦点移动到表单上的下一个控件。

初始化部分:

public Form1()
{
  InitializeComponent();

  cmbItems = new List<ComboBoxItem>();
  InitializeComboBox();

}

private void InitializeComboBox()
{
  Random rand = new Random();
  for (int i = 0; i <= 1500; i++)
  {
    int counter = rand.Next(1, 105000);
    cmbItems.Add(new ComboBoxItem("randomNumber" + counter, "ID_" + counter));
  }
  comboBox1.DataSource = cmbItems;
}

过滤部分:

private void comboBox1_TextUpdate(object sender, EventArgs e)
{

  if (comboBox1.Text == string.Empty)
  {
    comboBox1.DataSource = cmbItems; // cmbItems is a List of ComboBoxItem with some random numbers
    comboBox1.SelectedIndex = -1;
  }
  else
  {
    string tempStr = comboBox1.Text;
    IEnumerable<ComboBoxItem> data = (from m in cmbItems where m.Label.ToLower().Contains(tempStr.ToLower()) select m);

    comboBox1.DataSource = null;
    comboBox1.Items.Clear();

    foreach (var temp in data)
    {
      comboBox1.Items.Add(temp);
    }
    comboBox1.DroppedDown = true;
    Cursor.Current = Cursors.Default;
    comboBox1.SelectedIndex = -1;

    comboBox1.Text = tempStr;
    comboBox1.Select(comboBox1.Text.Length, 0);

  }
}

移动焦点部分:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  if (e.KeyChar != '\r') return;

  if (this.ActiveControl != null)
  {
    this.SelectNextControl(this.ActiveControl, true, true, true, true);
  }
  e.Handled = true; // Mark the event as handled
}

我希望对某人有所帮助。