简体   繁体   中英

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.

在此处输入图片说明

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

在此处输入图片说明

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!

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;
        }
    }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM