🔒 Closed Search and Select Item In ListBox with LINQ [Tutorial 1]

Status
Not open for further replies.
Dahil may nakita akong question about searching in listbox, so I made a simple LINQ code which is easy to undestand and use :)

Quick demo:
download


Here's the code:

C#:
private void button1_Click(object sender, EventArgs e)
{
    SearchItems(textBox1.Text);
}
//Enter keypress
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) {
        SearchItems(textBox1.Text);
    }
}

//Search function
private void SearchItems(string searchString)
{
    var i = listBox1.Items.Cast<string>().ToList()
      .Where(item => item.Contains(searchString)).ToList();
     //or item.Equals if you want specific words only
    i.ForEach(x => listBox1.SetSelected(listBox1.Items.IndexOf(x), true));
    i.ForEach(x => textBox2.Text = x.ToString());

    textBox1.SelectAll();
}
 
Status
Not open for further replies.

About this Thread

  • 0
    Replies
  • 614
    Views
  • 1
    Participants
Last reply from:
zackmark29

Online now

Members online
991
Guests online
931
Total visitors
1,922

Forum statistics

Threads
2,276,237
Posts
28,968,536
Members
1,231,176
Latest member
johnwindeel
Back
Top