Список поиска для элемента, содержащего строку - PullRequest
4 голосов
/ 07 июня 2011

Справочная информация : я создаю приложение базы данных для хранения информации о моей огромной коллекции фильмов. Список содержит сотни элементов, поэтому я решил реализовать функцию поиска, которая бы выделяла все элементы, содержащие определенную строку. Иногда трудно вспомнить название всего фильма, поэтому я подумал, что это пригодится.

Я нашел этот полезный код на сайте Microsoft, который выделяет все элементы в списке, которые содержат определенную строку. Как я могу изменить его для поиска по каждой строке полностью?

В настоящее время код ищет только те элементы, которые начинают со строки поиска, вместо того, чтобы видеть, содержит ли она строку поиска где-либо еще. Я натолкнулся на метод listbox.items.contains () в Google, хотя понятия не имею, как преобразовать для него свой код.

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 ]

4 голосов
/ 07 июня 2011

Создайте свою собственную функцию поиска, что-то вроде

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

(будьте осторожны, я написал это из своей головы без компиляции или тестирования, код может содержать ошибки, но я думаю, что вы поймете идею !!!)

0 голосов
/ 04 июля 2013

только один лайнер

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

:) С уважением

0 голосов
/ 28 июля 2011

Был задан тот же вопрос: Поиск в ListBox и выбор результата в C #

Я предлагаю другое решение:

  1. Не подходит для списка>1000 предметов.

  2. Каждая итерация повторяет все элементы.

  3. Находит и остается в наиболее подходящем случае.

    <code> 
        // 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++;
                    }
                }
            }
        }</p>
    
    <p>

Надеюсь, эта помощь!

0 голосов
/ 07 июня 2011

Как насчет ниже.Вам просто нужно немного его улучшить

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

        }
    }
}
0 голосов
/ 07 июня 2011

Я не уверен насчет кода, который вы разместили, но я написал небольшой метод, чтобы сделать то, что вы ищете.Это очень просто:

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

    }
0 голосов
/ 07 июня 2011

Используйте 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);
        }
    }
}

Я также предлагаю вам установить свойство SelectionMode ListBox в конструкторе Winform или в методе конструктора форм.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...