Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Select Item in ListView Programmatically

I have this to show all records from database to 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() }));
                }
            }
        }
    }

For example I have this result:

EmpID  |  Lname  |  Fname
40001  |  Smith  |  John
40002  |  Jones  |  David
40003  |  Bryan  |  Kobe

How I will programmatically select an item from the list above? For example I type 40002 in the textBox then this will be selected 40002 | Jones | David

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to handle the TextChanged event of your 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.
        }
}

You can also use ListView.FindItemWithText method, but notice that it matches the exact string which starts the item text, that means you have to handle the case-sensivity yourself in case you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...