RichTextBox.GetLineFromCharIndex(Int32) Метод

Определение

Извлекает номер строки по указанному местоположению символа в тексте элемента управления 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

Параметры

index
Int32

Местоположение индекса символа для поиска.

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

Отсчитываемый от нуля номер строки, на которую указывает индекс символа.

Примеры

В следующем примере кода показано использование GetLineFromCharIndex метода . Чтобы запустить пример, вставьте следующий код в форму, содержащую RichTextBox элемент управления с именем RichTextBox1, кнопку с именем Button1 и два текстовых поля с именем TextBox1 и TextBox2. При выполнении примера введите строку поиска в TextBox2 и нажмите кнопку, чтобы получить результаты поиска.

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

Комментарии

Этот метод позволяет определить номер строки на основе символьного индекса, указанного index в параметре метода . Первая строка текста в элементе управления возвращает нулевое значение. Метод GetLineFromCharIndex возвращает номер физической строки, в которой индексированные символы находятся в элементе управления . Например, если часть первой логической строки текста в элементе управления переносится в следующую строку, метод возвращает значение 1, GetLineFromCharIndex если символ по указанному индексу символов был заключен во вторую физическую строку. Если WordWrap задано значение false, ни часть строки не переносится на следующую, а метод возвращает 0 для указанного символьного индекса. Этот метод можно использовать для определения строки, в которой находится определенный индекс символов. Например, после вызова Find метода для поиска текста можно получить индекс символов, в котором находятся результаты поиска. Этот метод можно вызвать с символьным индексом, возвращаемым методом Find , чтобы определить, в какой строке было найдено слово.

В некоторых случаях не создает исключение, GetLineFromCharIndex если index параметр является недопустимым значением. Пример:

  • index Если параметр имеет значение MinValue или -1, GetLineFromCharIndex возвращается значение 0.

  • index Если параметр имеет длину текста или MaxValue, GetLineFromCharIndex возвращает номер последней строки текста, который не обязательно Lines.Length-1совпадает с , в зависимости от значения WordWrap свойства .

В таких случаях проверьте входные данные перед вызовом GetLineFromCharIndex.

Примечание

Если индекс символов, указанный в параметре index , превышает доступное количество строк, содержащихся в элементе управления , возвращается номер последней строки.

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

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