ListBox.FindStringExact Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Находит первый элемент в ListBox том, что точно соответствует указанной строке.
Перегрузки
| Имя | Описание |
|---|---|
| FindStringExact(String) |
Находит первый элемент в ListBox том, что точно соответствует указанной строке. |
| FindStringExact(String, Int32) |
Находит первый элемент в ListBox том, что точно соответствует указанной строке. Поиск начинается с определенного начального индекса. |
FindStringExact(String)
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
Находит первый элемент в ListBox том, что точно соответствует указанной строке.
public:
int FindStringExact(System::String ^ s);
public int FindStringExact(string s);
member this.FindStringExact : string -> int
Public Function FindStringExact (s As String) As Integer
Параметры
- s
- String
Текст для поиска.
Возвращаемое значение
Отсчитываемый от нуля индекс первого найденного элемента; возвращается ListBox.NoMatches , если совпадение не найдено.
Примеры
В следующем примере кода показано, как использовать ListBox.FindStringExact метод для поиска ListBox элемента управления, точно соответствующего указанной строке. Если элементы не найдены, соответствующие строке поиска, FindStringExact возвращает значение -1, а в примере отображается значение MessageBox. Если элемент найден, соответствующий тексту поиска, в примере используется SetSelected метод для выбора элемента в элементе ListBox.
private:
void FindMySpecificString( 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->FindStringExact( searchString );
// Determine if a valid index is returned. Select the item if it is valid.
if ( index != ListBox::NoMatches )
listBox1->SetSelected( index, true );
else
MessageBox::Show( "The search string did not find any items in the ListBox that exactly match the specified search string" );
}
}
private void FindMySpecificString(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.FindStringExact(searchString);
// Determine if a valid index is returned. Select the item if it is valid.
if (index != ListBox.NoMatches)
listBox1.SetSelected(index,true);
else
MessageBox.Show("The search string did not find any items in the ListBox that exactly match the specified search string");
}
}
Private Sub FindMySpecificString(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.FindStringExact(searchString)
' Determine if a valid index is returned. Select the item if it is valid.
If index <> ListBox.NoMatches Then
listBox1.SetSelected(index, True)
Else
MessageBox.Show("The search string did not find any items in the ListBox that exactly match the specified search string")
End If
End If
End Sub
Комментарии
Поиск, выполняемый этим методом, не учитывает регистр. Поиск ищет точное совпадение с словами, указанными в параметре строки поиска. s Этот метод можно использовать для поиска первого элемента, соответствующего указанной строке. Затем можно выполнять такие задачи, как удаление элемента, содержащего текст поиска, с помощью Remove метода или изменения текста элемента. После того как вы нашли указанный текст, если вы хотите искать другие экземпляры текста, ListBoxможно использовать версию FindStringExact метода, которая предоставляет параметр для указания начального индекса в пределах.ListBox Если вы хотите выполнить частичный поиск слов вместо точного совпадения слов, используйте FindString этот метод.
См. также раздел
Применяется к
FindStringExact(String, Int32)
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
- Исходный код:
- ListBox.cs
Находит первый элемент в ListBox том, что точно соответствует указанной строке. Поиск начинается с определенного начального индекса.
public:
int FindStringExact(System::String ^ s, int startIndex);
public int FindStringExact(string s, int startIndex);
member this.FindStringExact : string * int -> int
Public Function FindStringExact (s As String, startIndex As Integer) As Integer
Параметры
- s
- String
Текст для поиска.
- startIndex
- Int32
Отсчитываемый от нуля индекс элемента перед поиском первого элемента. Задайте для отрицательного значения (-1) поиск с самого начала элемента управления.
Возвращаемое значение
Отсчитываемый от нуля индекс первого найденного элемента; возвращается ListBox.NoMatches , если совпадение не найдено.
Исключения
Параметр startIndex меньше нуля или больше или равен значению Count свойства ListBox.ObjectCollection класса.
Примеры
В следующем примере кода показано, как использовать FindStringExact метод для поиска всех элементов в ListBox указанном тексте поиска. В примере используется версия FindStringExact метода, которая позволяет указать начальный индекс поиска, из которого выполняется непрерывный поиск всех элементов в элементе ListBox. В примере также показано, как определить, когда FindStringExact метод начинает поиск в верхней части списка после достижения нижней части списка элементов, чтобы предотвратить рекурсивный поиск. После того как элементы будут найдены в объектеListBoxSetSelected, они выбираются с помощью метода.
private:
void FindAllOfMyExactStrings( 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->FindStringExact( searchString, x );
// If no item is found that matches exit.
if ( x != -1 )
{
// Since the FindStringExact 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 FindAllOfMyExactStrings(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.FindStringExact(searchString, x);
// If no item is found that matches exit.
if (x != -1)
{
// Since the FindStringExact 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 FindAllOfMyExactStrings(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.FindStringExact(searchString, x)
' If no item is found that matches exit.
If x <> -1 Then
' Since the FindStringExact 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 параметре элемента после первого найденного экземпляра текста поиска. Если вы хотите выполнить частичный поиск слов вместо точного совпадения слов, используйте FindString этот метод.
Note
Когда поиск достигает нижней ListBoxчасти, он продолжает поиск в верхней части ListBox спины к элементу, указанному параметром startIndex .