RichTextBox.GetLineFromCharIndex(Int32) Método

Definición

Recupera el número de línea a partir de la posición de carácter especificada en el texto del control RichTextBox.

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

Posición del índice de carácter que se va a buscar.

Devoluciones

Número de línea de base cero donde se encuentra el índice de carácter.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetLineFromCharIndex método . Para ejecutar el ejemplo, pegue el código siguiente en un formulario que contiene un RichTextBox control denominado , un botón denominado RichTextBox1Button1 y dos cuadros de texto denominados TextBox1 y TextBox2. Cuando se ejecute el ejemplo, escriba una cadena de búsqueda en y haga clic en TextBox2 el botón para obtener los resultados de la búsqueda.

// 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

Comentarios

Este método permite determinar el número de línea en función del índice de caracteres especificado en el index parámetro del método . La primera línea de texto del control devuelve el valor cero. El GetLineFromCharIndex método devuelve el número de línea física donde se encuentra el carácter indizado dentro del control . Por ejemplo, si una parte de la primera línea lógica de texto del control se ajusta a la siguiente línea, el GetLineFromCharIndex método devuelve 1 si el carácter del índice de caracteres especificado se ha ajustado a la segunda línea física. Si WordWrap se establece falseen , ninguna parte de la línea se ajusta a la siguiente y el método devuelve 0 para el índice de caracteres especificado. Puede usar este método para determinar en qué línea se encuentra un índice de caracteres específico. Por ejemplo, después de llamar al Find método para buscar texto, puede obtener el índice de caracteres a donde se encuentran los resultados de la búsqueda. Puede llamar a este método con el índice de caracteres devuelto por el Find método para determinar qué línea se encontró la palabra.

En determinados casos, GetLineFromCharIndex no produce una excepción cuando el index parámetro es un valor no válido. Por ejemplo:

En estos casos, valide la entrada antes de llamar a GetLineFromCharIndex.

Nota:

Si el índice de caracteres especificado en el index parámetro está más allá del número disponible de líneas contenidas en el control, se devuelve el último número de línea.

Se aplica a

Consulte también