ListBox.FindString Метод

Определение

Находит первый элемент в ListBox начале указанной строки.

Перегрузки

Имя Описание
FindString(String)

Находит первый элемент в ListBox начале указанной строки.

FindString(String, Int32)

Находит первый элемент в ListBox начале указанной строки. Поиск начинается с определенного начального индекса.

FindString(String)

Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs

Находит первый элемент в ListBox начале указанной строки.

public:
 int FindString(System::String ^ s);
public int FindString(string s);
member this.FindString : string -> int
Public Function FindString (s As String) As Integer

Параметры

s
String

Текст для поиска.

Возвращаемое значение

Отсчитываемый от нуля индекс первого найденного элемента; возвращается ListBox.NoMatches , если совпадение не найдено.

Исключения

Значение s параметра меньше -1 или больше или равно числу элементов.

Примеры

В следующем примере кода показано, как использовать FindString метод для поиска первого экземпляра строки в объекте ListBox. Если элементы не найдены, соответствующие строке FindString поиска, возвращает значение -1, а в примере отображается значение MessageBox. Если элемент найден, соответствующий тексту поиска, в примере используется SetSelected метод для выбора элемента в элементе ListBox.

private:
   void FindMyString( String^ searchString )
   {
      // Ensure we have a proper string to search for.
      if ( searchString != String::Empty )
      {
         // Find the item in the list and store the index to the item.
         int index = listBox1->FindString( searchString );

         // Determine if a valid index is returned. Select the item if it is valid.
         if ( index != -1 )
                  listBox1->SetSelected( index, true );
         else
                  MessageBox::Show( "The search string did not match any items in the ListBox" );
      }
   }
private void FindMyString(string searchString)
{
   // Ensure we have a proper string to search for.
   if (!string.IsNullOrEmpty(searchString))
   {
      // Find the item in the list and store the index to the item.
      int index = listBox1.FindString(searchString);
      // Determine if a valid index is returned. Select the item if it is valid.
      if (index != -1)
         listBox1.SetSelected(index,true);
      else
         MessageBox.Show("The search string did not match any items in the ListBox");
   }
}
Private Sub FindMyString(ByVal searchString As String)
   ' Ensure we have a proper string to search for.
   If searchString <> String.Empty Then
      ' Find the item in the list and store the index to the item.
      Dim index As Integer = listBox1.FindString(searchString)
      ' Determine if a valid index is returned. Select the item if it is valid.
      If index <> -1 Then
         listBox1.SetSelected(index, True)
      Else
         MessageBox.Show("The search string did not match any items in the ListBox")
      End If
   End If
End Sub

Комментарии

Поиск, выполняемый этим методом, не учитывает регистр. Поиск ищет слова, которые частично соответствуют указанному параметру строки поиска. s Этот метод можно использовать для поиска первого элемента, соответствующего указанной строке. Затем можно выполнять такие задачи, как удаление элемента, содержащего текст поиска, с помощью Remove метода или изменения текста элемента. После того как вы нашли указанный текст, если вы хотите искать другие экземпляры текста, ListBoxможно использовать версию FindString метода, которая предоставляет параметр для указания начального индекса в пределах.ListBox Если вы хотите выполнить поиск точного совпадения слов вместо частичного совпадения, используйте FindStringExact этот метод.

См. также раздел

Применяется к

FindString(String, Int32)

Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs
Исходный код:
ListBox.cs

Находит первый элемент в ListBox начале указанной строки. Поиск начинается с определенного начального индекса.

public:
 int FindString(System::String ^ s, int startIndex);
public int FindString(string s, int startIndex);
member this.FindString : string * int -> int
Public Function FindString (s As String, startIndex As Integer) As Integer

Параметры

s
String

Текст для поиска.

startIndex
Int32

Отсчитываемый от нуля индекс элемента перед поиском первого элемента. Задайте для отрицательного значения (-1) поиск с самого начала элемента управления.

Возвращаемое значение

Отсчитываемый от нуля индекс первого найденного элемента; возвращается ListBox.NoMatches , если совпадение не найдено.

Исключения

Параметр startIndex меньше нуля или больше или равен значению Count свойства ListBox.ObjectCollection класса.

Примеры

В следующем примере кода показано, как использовать FindString метод для поиска всех экземпляров текста поиска в элементах.ListBox В примере используется версия FindString метода, которая позволяет указать начальный индекс поиска, из которого выполняется непрерывный поиск всех элементов в элементе ListBox. В примере также показано, как определить, когда FindString метод начинает поиск в верхней части списка после достижения нижней части списка элементов, чтобы предотвратить рекурсивный поиск. После того как элементы будут найдены в объектеListBoxSetSelected, они выбираются с помощью метода.

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 );
      }
   }
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);
   }
}
Private Sub FindAllOfMyString(ByVal searchString As String)
   ' Set the SelectionMode property of the ListBox to select multiple items.
   listBox1.SelectionMode = SelectionMode.MultiExtended

   ' Set our intial index variable to -1.
   Dim x As Integer = -1
   ' If the search string is empty exit.
   If searchString.Length <> 0 Then
      ' 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 Then
            ' Since the FindString loops infinitely, determine if we found first item again and exit.
            If ListBox1.SelectedIndices.Count > 0 Then
               If x = ListBox1.SelectedIndices(0) Then
                  Return
               End If
            End If
            ' Select the item in the ListBox once it is found.
            ListBox1.SetSelected(x, True)
         End If
      Loop While x <> -1
   End If
End Sub

Комментарии

Поиск, выполняемый этим методом, не учитывает регистр. Поиск ищет слова, которые частично соответствуют указанному параметру строки поиска. s Этот метод можно использовать для поиска первого элемента, соответствующего указанной строке в указанном начальном индексе в списке элементов.ListBox Затем можно выполнять такие задачи, как удаление элемента, содержащего текст поиска, с помощью Remove метода или изменения текста элемента. Этот метод обычно используется после вызова с использованием версии этого метода, которая не указывает начальный индекс. После того как исходный элемент найден в списке, этот метод обычно используется для поиска дополнительных экземпляров текста поиска путем указания позиции индекса в startIndex параметре элемента после первого найденного экземпляра текста поиска. Если вы хотите выполнить поиск точного совпадения слов вместо частичного совпадения, используйте FindStringExact этот метод.

Note

Когда поиск достигает нижней ListBoxчасти, он продолжает поиск в верхней части ListBox спины к элементу, указанному параметром startIndex .

См. также раздел

Применяется к