使用 C# 窗口窗体中的文本搜索筛选组合框项
本文关键字:筛选 搜索 组合 文本 窗口 窗体 使用 | 更新日期: 2023-09-27 18:36:30
>我正在尝试使用其文本属性在项目的所有字符中过滤组合框,而不仅仅是它们的开头。我正在组合框的 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
}
我希望这对某人有所帮助。
您可以在表单中添加文本框并使用它的文本来过滤:
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;