通过文本框搜索数据库并在列表视图中显示结果 [英] Searching database through textbox and show the result in a listview
本文介绍了通过文本框搜索数据库并在列表视图中显示结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用textchanged事件将文本放入文本框时,listview会反复显示数据。
我尝试了什么:
i已在此处使用此代码,
When i put a text into a textbox using textchanged event the listview shows data repeatedly .
What I have tried:
i have already used this code below here ,
string name = textboxsearch.Text;
if (textboxsearch.Text != "")
{
con.Open();
string str = "select * from all_record where title like'" + name + "%'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
OleDbDataReader dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
listView1.Visible = true;
ListViewItem item = new ListViewItem(dr1["title"].ToString());
item.SubItems.Add(dr1["last_name"].ToString());
item.SubItems.Add(dr1["Age"].ToString());
listView1.Items.Add(item);
}
dr1.Close();
}
else
{
listView1.Visible = false;
listView1.Items.Clear();
}
con.Close();
}
else
{
listView1.Visible = false;
listView1.Items.Clear();
}
推荐答案
试试这个
不需要两个数据引导器。并且最好在事件调用中清除最初的值,这样重复就不会存在。
try this
two datareaders is not necessary. and its good to clear the values initially on the event call, so that duplicates wont be there.
string name = textboxsearch.Text;
listView1.Visible = false;
listView1.Items.Clear();
if (name != "")
{
con.Open();
string str = "select * from all_record where title like'@name%'";
OleDbCommand cmd = new OleDbCommand(str, con);
cmd.Parameters.Add("@name",name);
OleDbDataReader dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
listView1.Visible = true;
ListViewItem item = new ListViewItem(dr1["title"].ToString());
item.SubItems.Add(dr1["last_name"].ToString());
item.SubItems.Add(dr1["Age"].ToString());
listView1.Items.Add(item);
}
dr1.Close();
con.Close();
}
}
请参阅 sql injection [ ^ ]
这篇关于通过文本框搜索数据库并在列表视图中显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文