我有这个来显示从数据库到listview的所有记录
private void populatelistview()
{
listView1.Items.Clear();
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select * from Employee", myDatabaseConnection))
{
SqlCommand.CommandType = CommandType.Text;
SqlDataReader dr = SqlCommand.ExecuteReader();
while (dr.Read())
{
listView1.Items.Add(new ListViewItem(new string[] { dr["EmpID"].ToString(), dr["Lname"].ToString(), dr["Fname"].ToString() }));
}
}
}
}
例如我有这个结果:
EmpID | Lname | Fname
40001 | Smith | John
40002 | Jones | David
40003 | Bryan | Kobe
我将如何以编程方式从上面的列表中选择一个项目?例如,我在textBox中输入40002,然后选择40002 | Jones | David
答案 0 :(得分:3)
您必须处理TextChanged
的{{1}}事件:
TextBox
您也可以使用//TextChanged event handler for your textBox1
private void textBox1_TextChanged(object sender, EventArgs e) {
ListViewItem item = listView1.Items.OfType<ListViewItem>()
.FirstOrDefault(x => x.Text.Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase));
if (item != null){
listView1.SelectedItems.Clear();
item.Selected = item.Focused = true;
listView1.Focus();//Focus to see it in action because SelectedItem won't look like selected if the listView is not focused.
}
}
方法,但请注意它与启动项目文字的确切字符串相匹配,这意味着您必须自己处理案例敏感度以防万一