-1

我有这个来显示从数据库到列表视图的所有记录

   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

4

1 回答 1

3

你必须处理你的TextChanged事件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.
        }
}

您也可以使用ListView.FindItemWithText方法,但请注意它与开始项目 text 的确切字符串匹配,这意味着您必须自己处理区分大小写以防万一。

于 2013-09-08T16:58:36.227 回答