如何根据变量搜索列表框项目



我是c#的新手,正在尝试搜索列表框,如下所示:首先我有这个:

public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(@"Server = AMR-PCSQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}

并试图做到这一点:

private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}

它不起作用,我试图创建一个新的sql选择查询,根据txtSrch.Text获取数据,但也一无所获。提前谢谢。

编辑#1这是我之前提到的查询:

private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(@"Server = AMR-PCSQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}

这不会影响列表框中的项目txtSrch更改时不会发生任何事情。

另一个使用Dataview的解决方案,感谢@Trevor

public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(@"Server = AMR-PCSQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}

文本框更改:

private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}

谢谢。

Basedon@Olivier Jacobt Descombes的评论,这对我有效:

private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(@"Server = AMR-PCSQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}

相关内容

  • 没有找到相关文章