首页 文章

如何在c#winforms中的列表框中搜索时突出显示所选项目?

提问于
浏览
0

我有一个由一些项填充的列表框,该表单包含文本框和列表框 . 在文本框中,用户可以在列表框中搜索指定的条目 . 现在,如果用户在文本框中键入某些文本,则列表中会显示已过滤的列表框项目 . 现在,假设我之前在搜索之前选择了列表框中的任何项目,那么如果我搜索列表框,我最后选择的元素(如果它存在于过滤的项目中)不会突出显示 . 如果它存在,我如何在筛选列表中显示我的持续选定项目 .

示例 - 在列表框中搜索之前 .

enter image description here

搜索列表后,我在筛选列表中存在的最后一个选定项目将丢失显示选择 .

enter image description here

我搜索列表框的代码 -

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

此外,我已选择在此列表框中应用的索引更改事件处理程序,我不想再次为筛选列表视图触发它 . 我只是想在过滤列表中突出显示它 .

谢谢!

1 回答

  • 1

    您可以保存在键入之前选择的项目以及在其余项目中搜索它,然后将该项目设置为选中(如果存在) .

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

相关问题