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

本文关键字:列表 搜索 项目 字符串 包含 | 更新日期: 2023-09-27 17:58:39

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

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

目前,代码只搜索以搜索字符串开头的项目,而不查看它是否在其他地方包含搜索字符串。我在谷歌上发现了一个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;
}

(注意,我在没有编译或测试的情况下就写了这篇文章,代码可能包含错误,但我想你会明白的!!)

使用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属性。

我不确定你发布的代码,但我写了一个小方法来做你想要的事情。它非常简单:

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

下面的内容如何。你只需要改进一下

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

问了同样的问题:在C#中搜索列表框并选择结果

我提出了另一个解决方案:

  1. 不适合列表框>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++;
                    }
                }
            }
        }

Hope this help!

just one liner

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

:)问候