RichTextBox.GetLineFromCharIndex(Int32) Método

Definição

Recupera o número da linha da posição especificada do carácter dentro do texto do RichTextBox controlo.

public:
 int GetLineFromCharIndex(int index);
public:
 override int GetLineFromCharIndex(int index);
public int GetLineFromCharIndex(int index);
public override int GetLineFromCharIndex(int index);
member this.GetLineFromCharIndex : int -> int
override this.GetLineFromCharIndex : int -> int
Public Function GetLineFromCharIndex (index As Integer) As Integer
Public Overrides Function GetLineFromCharIndex (index As Integer) As Integer

Parâmetros

index
Int32

A posição do índice de caracteres para pesquisar.

Devoluções

O número de linha em base zero onde se encontra o índice de caracteres.

Exemplos

O exemplo de código seguinte demonstra o uso do GetLineFromCharIndex método. Para executar o exemplo, cole o seguinte código numa forma contendo um RichTextBox controlo chamado RichTextBox1, um botão nomeado Button1 e duas caixas de texto nomeadas TextBox1 e TextBox2. Quando o exemplo estiver a correr, introduza uma cadeia TextBox2 de pesquisa e clique no botão para obter os resultados.

// This method demonstrates retrieving line numbers that 
// indicate the location of a particular word
// contained in a RichTextBox. The line numbers are zero-based.
void Button1_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
   
   // Reset the results box.
   TextBox1->Text = "";
   
   // Get the word to search from from TextBox2.
   String^ searchWord = TextBox2->Text;
   int index = 0;
   
   //Declare an ArrayList to store line numbers.
   System::Collections::ArrayList^ lineList = gcnew System::Collections::ArrayList;
   do
   {
      // Find occurrences of the search word, incrementing  
      // the start index. 
      index = RichTextBox1->Find( searchWord, index + 1, RichTextBoxFinds::MatchCase );
      if ( index != -1 )
      {
         lineList->Add( RichTextBox1->GetLineFromCharIndex( index ) );
      }
   }
   while ( (index != -1) );

   // Iterate through the list and display the line numbers in TextBox1.
   System::Collections::IEnumerator^ myEnumerator = lineList->GetEnumerator();
   if ( lineList->Count <= 0 )
   {
      TextBox1->Text = searchWord + " was not found";
   }
   else
   {
      TextBox1->SelectedText = searchWord + " was found on line(s):";
      while ( myEnumerator->MoveNext() )
      {
         TextBox1->SelectedText = myEnumerator->Current + " ";
      }
   }
}
// This method demonstrates retrieving line numbers that 
// indicate the location of a particular word
// contained in a RichTextBox. The line numbers are zero-based.

private void Button1_Click(System.Object sender, System.EventArgs e)
{

    // Reset the results box.
    TextBox1.Text = "";

    // Get the word to search from from TextBox2.
    string searchWord = TextBox2.Text;

    int index = 0;

    //Declare an ArrayList to store line numbers.
    System.Collections.ArrayList lineList = new System.Collections.ArrayList();
    do
    {
        // Find occurrences of the search word, incrementing  
        // the start index. 
        index = RichTextBox1.Find(searchWord, index+1, RichTextBoxFinds.MatchCase);
        if (index!=-1)

            // Find the word's line number and add the line 
            // number to the arrayList. 
        {
            lineList.Add(RichTextBox1.GetLineFromCharIndex(index));
        }
    }
    while((index!=-1));

    // Iterate through the list and display the line numbers in TextBox1.
    System.Collections.IEnumerator myEnumerator = lineList.GetEnumerator();
    if (lineList.Count<=0)
    {
        TextBox1.Text = searchWord+" was not found";
    }
    else
    {
        TextBox1.SelectedText = searchWord+" was found on line(s):";
        while (myEnumerator.MoveNext())
        {
            TextBox1.SelectedText = myEnumerator.Current+" ";
        }
    }
}
' This method demonstrates retrieving line numbers that 
' indicate the location of a particular word
' contained in a RichTextBox. The line numbers are zero-based.

Private Sub Button1_Click(ByVal sender As System.Object, _ 
    ByVal e As System.EventArgs) Handles Button1.Click

    ' Reset the results box.
    TextBox1.Text = ""

    ' Get the word to search from from TextBox2.
    Dim searchWord As String = TextBox2.Text

    Dim index As Integer = 0

    'Declare an ArrayList to store line numbers.
    Dim lineList As New System.Collections.ArrayList
    Do
        ' Find occurrences of the search word, incrementing  
        ' the start index. 
        index = RichTextBox1.Find(searchWord, index + 1, _
            RichTextBoxFinds.MatchCase)
        If (index <> -1) Then

            ' Find the word's line number and add the line 
            'number to the arrayList. 
            lineList.Add(RichTextBox1.GetLineFromCharIndex(index))
        End If
    Loop While (index <> -1)

    ' Iterate through the list and display the line numbers in TextBox1.
    Dim myEnumerator As System.Collections.IEnumerator = _
        lineList.GetEnumerator()
    If lineList.Count <= 0 Then
        TextBox1.Text = searchWord & " was not found"
    Else
        TextBox1.SelectedText = searchWord & " was found on line(s):"
        While (myEnumerator.MoveNext)
            TextBox1.SelectedText = myEnumerator.Current & " "
        End While
    End If

End Sub

Observações

Este método permite-lhe determinar o número da linha com base no índice de caracteres especificado no index parâmetro do método. A primeira linha de texto no controlo devolve o valor zero. O GetLineFromCharIndex método devolve o número físico da linha onde o carácter indexado está localizado dentro do controlo. Por exemplo, se uma parte da primeira linha lógica de texto no controlo enrolar para a linha seguinte, o GetLineFromCharIndex método retorna 1 se o carácter no índice especificado tiver sido enrolado para a segunda linha física. Se WordWrap for definido para false, nenhuma parte da linha passa para a seguinte, e o método devolve 0 para o índice de caracteres especificado. Pode usar este método para determinar em que linha se encontra um índice de caracteres específico. Por exemplo, depois de chamar o Find método para pesquisar texto, pode obter o índice de caracteres onde os resultados da pesquisa são encontrados. Pode chamar este método com o índice de caracteres devolvido pelo Find método para determinar que linha a palavra foi encontrada.

Em certos casos, GetLineFromCharIndex não lança uma exceção quando o index parâmetro é um valor inválido. Por exemplo:

Nestes casos, valida a entrada antes de chamar GetLineFromCharIndex.

Note

Se o índice de caracteres especificado no index parâmetro ultrapassar o número disponível de linhas contidas no controlo, o último número de linha é devolvido.

Aplica-se a

Ver também