ListBox.FindString Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Encontra o primeiro item do ListBox que começa com a cadeia especificada.
Sobrecargas
| Name | Description |
|---|---|
| FindString(String) |
Encontra o primeiro item do ListBox que começa com a cadeia especificada. |
| FindString(String, Int32) |
Encontra o primeiro item do ListBox que começa com a cadeia especificada. A pesquisa começa num índice inicial específico. |
FindString(String)
Encontra o primeiro item do ListBox que começa com a cadeia especificada.
public:
int FindString(System::String ^ s);
public int FindString(string s);
member this.FindString : string -> int
Public Function FindString (s As String) As Integer
Parâmetros
- s
- String
O texto a procurar.
Devoluções
O índice em base zero do primeiro item encontrado; Retorna ListBox.NoMatches se não for encontrada correspondência.
Exceções
O valor do s parâmetro é inferior a -1 ou superior ou igual ao número de itens.
Exemplos
O exemplo de código seguinte demonstra como usar o FindString método para procurar a primeira instância de uma cadeia em um ListBox. Se não forem encontrados itens que correspondam, a cadeia FindString de pesquisa devolve um valor -1 e o exemplo mostra um MessageBox. Se for encontrado um item que corresponde ao texto da pesquisa, o exemplo utiliza o SetSelected método para selecionar o item no ListBoxarquivo .
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
Observações
A pesquisa realizada por este método não é sensível a maiúsculas minúsculas. A pesquisa procura palavras que correspondam parcialmente ao parâmetro especificado da cadeia de pesquisa, s. Podes usar este método para procurar o primeiro item que corresponda à string especificada. Pode então realizar tarefas como remover o item que contém o texto da pesquisa usando o Remove método ou alterar o texto do item. Depois de encontrar o texto especificado, se quiser procurar outras instâncias do texto no ListBox, pode usar a versão do FindString método que fornece um parâmetro para especificar um índice inicial dentro do ListBox. Se quiser fazer uma pesquisa por uma correspondência exata de palavras em vez de uma correspondência parcial, use o FindStringExact método.
Ver também
Aplica-se a
FindString(String, Int32)
Encontra o primeiro item do ListBox que começa com a cadeia especificada. A pesquisa começa num índice inicial específico.
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
Parâmetros
- s
- String
O texto a procurar.
- startIndex
- Int32
O índice base zero do item antes do primeiro item a ser pesquisado. Defina para menos um (-1) para pesquisar desde o início do controlo.
Devoluções
O índice em base zero do primeiro item encontrado; Retorna ListBox.NoMatches se não for encontrada correspondência.
Exceções
O startIndex parâmetro é menor que zero ou maior ou igual ao valor da Count propriedade da ListBox.ObjectCollection classe.
Exemplos
O exemplo de código seguinte demonstra como usar o FindString método para pesquisar todas as instâncias do texto de pesquisa nos itens do ListBox. O exemplo utiliza a versão do FindString método que permite especificar um índice de pesquisa inicial a partir do qual fazer uma pesquisa contínua de todos os itens do ListBox. O exemplo também demonstra como determinar quando o FindString método começa a procurar no topo da lista depois de chegar ao fundo da lista de itens, para evitar uma pesquisa recursiva. Uma vez que os itens são encontrados no ListBox, são selecionados usando o SetSelected método.
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
Observações
A pesquisa realizada por este método não é sensível a maiúsculas minúsculas. A pesquisa procura palavras que correspondam parcialmente ao parâmetro especificado da cadeia de pesquisa, s. Pode usar este método para procurar o primeiro item que corresponde à string especificada no índice inicial especificado dentro da lista de itens para o ListBox. Pode então realizar tarefas como remover o item que contém o texto da pesquisa usando o Remove método ou alterar o texto do item. Este método é normalmente usado após uma chamada ter sido feita usando a versão deste método que não especifica um índice inicial. Uma vez encontrado um item inicial na lista, este método é normalmente usado para encontrar mais instâncias do texto de pesquisa, especificando a posição do índice no startIndex parâmetro do item após a primeira instância encontrada do texto de pesquisa. Se quiser fazer uma pesquisa por uma correspondência exata de palavras em vez de uma correspondência parcial, use o FindStringExact método.
Note
Quando a pesquisa chega ao fundo do ListBox, continua a procurar do topo do verso ListBox até ao item especificado pelo startIndex parâmetro.