搜索包含字符串的项目的列表框

时间:2011-06-07 15:10:20

标签: 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);
   }
}

6 个答案:

答案 0 :(得分:4)

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

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

(要注意,我在没有编译或测试的情况下写出来,代码可能包含错误,但我认为你会得到这个想法!!!)

答案 1 :(得分:0)

使用String.IndexOf对ListBox中的每个项目进行不区分大小写的字符串搜索:

private void FindAllOfMyString(string searchString) {
    for (int i = 0; i < listBox1.Items.Count; i++) {
        if (listBox1.Items[i].ToString().IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0) {
            listBox1.SetSelected(i, true);
        } else {
            // Do this if you want to select in the ListBox only the results of the latest search.
            listBox1.SetSelected(i, false);
        }
    }
}

我还建议你在Winform设计器或表单构造函数方法中设置ListBox的SelectionMode属性。

答案 2 :(得分:0)

我不确定你发布的代码,但我写了一个小方法来做你正在寻找的东西。这非常简单:

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.SelectionMode = SelectionMode.MultiSimple;
        IEnumerable items = listBox1.Items;
        List<int> indices = new List<int>();

        foreach (var item in items)
        {
            string movieName = item as string;

            if ((!string.IsNullOrEmpty(movieName)) && movieName.Contains(searchString))
            {
                indices.Add(listBox1.Items.IndexOf(item));
            }
        }
        indices.ForEach(index => listBox1.SelectedIndices.Add(index));

    }

答案 3 :(得分:0)

下面怎么样?你只需要改进一下

   using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class Item
    {
        public Item(string id,string desc)
        {
            id = id;
            Desc = desc;
        }
        public string Id { get; set; }
        public string Desc { get; set; }
    }

    public partial class Form1 : Form
    {
        public const string Searchtext="o";
        public Form1()
        {
            InitializeComponent();
            listBox1.SelectionMode = SelectionMode.MultiExtended;
        }

        public static List<Item> GetItems()
        {
            return new List<Item>()
                       {
                           new Item("1","One"),
                           new Item("2","Two"),
                           new Item("3","Three"),
                           new Item("4","Four")
                       };
        }


        private void Form1_Load(object sender, EventArgs e)
        {

            listBox1.DataSource = GetItems();
            listBox1.DisplayMember = "Desc";
            listBox1.ValueMember = "Id";
            listBox1.ClearSelected();
            listBox1.Items.Cast<Item>()
                .ToList()
                .Where(x => x.Desc.Contains("o")).ToList()
                .ForEach(x => listBox1.SetSelected(listBox1.FindString(x.Desc),true));

        }
    }
}

答案 4 :(得分:0)

同样的问题被问到: Search a ListBox and Select result in C#

我提出另一个解决方案:

  1. 不适合列表框&gt; 1000件。

  2. 每次迭代都会循环所有项目。

  3. 查找并保留最合适的案例。

     
        // Save last successful match.
        private int lastMatch = 0;
        // textBoxSearch - where the user inputs his search text
        // listBoxSelect - where we searching for text
        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            // Index variable.
            int x = 0;
            // Find string or part of it.
            string match = textBoxSearch.Text;
            // Examine text box length 
            if (textBoxSearch.Text.Length != 0)
            {
                bool found = true;
                while (found)
                {
                    if (listBoxSelect.Items.Count == x)
                    {
                        listBoxSelect.SetSelected(lastMatch, true);
                        found = false;
                    }
                    else
                    {
                        listBoxSelect.SetSelected(x, true);
                        match = listBoxSelect.SelectedValue.ToString();
                        if (match.Contains(textBoxSearch.Text))
                        {
                            lastMatch = x;
                            found = false;
                        }
                        x++;
                    }
                }
            }
        }

  4. 希望这有帮助!

答案 5 :(得分:-1)

只是一个班轮

 if(LISTBOX.Items.Contains(LISTBOX.Items.FindByText("anystring")))
//string found
else
//string not found

:)问候