【问题标题】:Search listbox for item containing a string搜索包含字符串的项目的列表框
【发布时间】:2011-09-10 04:13:05
【问题描述】:

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

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

【问题讨论】:

    标签: c# search listbox


    【解决方案1】:

    只有一个班轮

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

    :) 问候

    【讨论】:

      【解决方案2】:

      问了同样的问题: Search a ListBox and Select result in 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++;
                        }
                    }
                }
            }
        
        

      希望对您有所帮助!

      【讨论】:

        【解决方案3】:

        下面呢。你只需要改进一下

           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】:

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

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

          【讨论】:

            【解决方案5】:

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

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

            【讨论】:

              【解决方案6】:

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

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

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

              【讨论】:

                猜你喜欢
                • 2015-10-02
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-03-24
                • 1970-01-01
                • 2011-05-25
                • 2023-02-13
                • 1970-01-01
                相关资源
                最近更新 更多