c# - 在 C# Windows 窗体中使用文本搜索过滤组合框项目

标签 c# visual-studio-2012 combobox

我试图在项目的所有字符中使用其文本属性来过滤组合框,而不仅仅是它们的开头。我在我的组合框的 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”已定义并打开。 感谢您的帮助。

最佳答案

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

初始化部分:

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
}

希望对大家有所帮助。

关于c# - 在 C# Windows 窗体中使用文本搜索过滤组合框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784473/

相关文章:

javascript - Ext Js 2.1 组合框 Anymatch 过滤器不起作用

c# - 我必须删除处理程序吗

c# - 通过 C# 应用程序运行使用提示的 perl 脚本

c# - 禁用错误声音 visual studio 2012

unit-testing - 在Visual Studio测试中,如何制作自动排除某些测试的播放列表?

c# - 在 WPF MVVM 应用程序的 ComboBox 中设置默认选定项

c# wpf comboBox 在我输入第一个字母时选择列表中的项目

c# - 如何将浮点值从 MySQL 数据库获取到数据表中 | C#

c# - 在 WebBrowser 控件中设置 cookie

visual-studio-2012 - "SlowCheetah.Xdt.TransformXml"任务无法从程序集中加载