我试图在项目的所有字符中使用其文本属性来过滤组合框,而不仅仅是它们的开头。我在我的组合框的 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/