theburningfire
theburningfire

Reputation: 511

How to keep selected item highlighted while searching in listbox in c# winforms?

I have a list box that is populated by some items, the form contains textbox and a list box. In the textbox user can search for specified entry in list box. Now if user types in some text in textbox then filtered listbox items is shown in list. Now, Suppose if i have previously selected any item in listbox before search then if i search the list box my last selected element if it exists in filtered items is not shown highlighted. How can i show my lasted selected item highlighed in filtered list if it exists in it.

Example - Before searching in listbox.

enter image description here

After searching the list my last selected item if exists in filtered list loses the display selection.

enter image description here

My code for searching listbox -

 private void vmS_TextBox1_TextChanged(object sender, EventArgs e)
    {
        string keyword = this.iBoxEventlistSearchTextBox.Text;
        lBox_Event_list.Items.Clear();

        foreach (string item in sortedEventList)
        {
            if (item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                lBox_Event_list.Items.Add(item);
            }
        }
    }     

Also i have selected index change event handler applied on this list box any i don't want to fire it again for filtered list view. I just only want to show it highlighted on filtered list.

Thankyou!

Upvotes: 0

Views: 1504

Answers (1)

Ipsit Gaur
Ipsit Gaur

Reputation: 2927

You can save the item that was selected before typing and the searching for it in the remaining items and then set the item selected if present.

private void vmS_TextBox1_TextChanged(object sender, EventArgs e)
    {
        string keyword = this.iBoxEventlistSearchTextBox.Text;
        // Save the selected item before
        var selectedItem = string.Empty;
        if(lBox_Event_list?.Items?.Count > 0)
           selectedItem = lBox_Event_list.SelectedItem;
        lBox_Event_list.Items.Clear();

        foreach (string item in sortedEventList)
        {
            if (item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                lBox_Event_list.Items.Add(item);
            }
        }
        // Search for it in the items and set the selected item to that
        if(string.IsNullOrEmpty(selectedItem)) 
        {
          var index = lBox_Event_list?.Items?.IndexOf(selectedItem);
          if(index != -1)
              lBox_Event_list.SelectedIndex = index;
        }
    }  

Upvotes: 1

Related Questions