Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...