c# - 在列表框中搜索包含字符串的项目

标签 c# search listbox

背景:我正在构建一个数据库应用程序来存储有关我的大量电影收藏的信息。该列表框包含数百个项目,因此我决定实现一个搜索功能,该功能将突出显示包含特定字符串的所有项目。有时很难记住完整的电影片名,所以我认为这会派上用场。

我在 Microsoft 站点上找到了这段有用的代码,它突出显示了列表框中包含特定字符串的所有项目。我如何修改它以完全搜索每个字符串?

目前代码只搜索以搜索字符串开头的项目,而不是查看它是否在其他任何地方包含搜索字符串。我在 Google 上遇到了一种 listbox.items.contains() 方法,尽管我不知道如何为它转换我的代码。

http://forums.asp.net/t/1094277.aspx/1

private void FindAllOfMyString(string searchString)
{
   // Set the SelectionMode property of the ListBox to select multiple items.
   listBox1.SelectionMode = SelectionMode.MultiExtended;

   // Set our intial index variable to -1.
   int x =-1;
   // If the search string is empty exit.
   if (searchString.Length != 0)
   {
      // Loop through and find each item that matches the search string.
      do
      {
         // Retrieve the item based on the previous index found. Starts with -1 which searches start.
         x = listBox1.FindString(searchString, x);
         // If no item is found that matches exit.
         if (x != -1)
         {
            // Since the FindString loops infinitely, determine if we found first item again and exit.
            if (listBox1.SelectedIndices.Count > 0)
            {
               if(x == listBox1.SelectedIndices[0])
                  return;
            }
            // Select the item in the ListBox once it is found.
            listBox1.SetSelected(x,true);
         }

      }while(x != -1);
   }
}

最佳答案

创建您自己的搜索功能,类似于

int FindMyStringInList(ListBox lb,string searchString,int startIndex)
{
     for(int i=startIndex;i<lb.Items.Count;++i)
     {
         string lbString = lb.Items[i].ToString();
         if(lbString.Contains(searchString))
            return i;
     }
     return -1;
}

(请注意,我是在没有编译或测试的情况下凭头脑写的,代码可能包含错误,但我想你会明白的!!!)

关于c# - 在列表框中搜索包含字符串的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6267368/

相关文章:

c# - 什么是异步回调?

c# - 带条纹的照片

regex - BASH:搜索字符串并准确显示子字符串在其中出现的确切次数

c# - 在 C# 中模仿 findstr 功能的最佳方法是什么?

c# - 列表框重复项

c# - xml linq在同一节点中检索元素

javascript - 将 C# 3D 数组移植到 JS 3D 数组

java - 哪个集合最适合存储键值对,但我必须同时搜索键和值

vb.net - 更改列表框中包含绘制项目上特定字符串的特定项目的颜色

c# - 列表框未通过数据源更新