Getting the Page Number at the Current Scroll Location

When using TX Text Control in read-only mode, it might be required to display the page number of the currently visible page. In order to get the page number at the current input position, you just need to get the appropriate property from the InputPosition object.

But when scrolling through the pages, the actual input position is not changed, so that this property can't be used to get the page number.

But thanks to the flexible and powerful class library, it is very easy to retrieve the page number of the currently visible page.

In order to get the page number, we use the LineCollection to get the line in the middle of the visible TextControl. TX Text Control automatically factors the current scroll location into the calculation, so that we just need to pass the half of the control size to the GetItem method. It returns the Line object in the middle of the visible document part. And the Line object provides the according page number among other information.

[C#]
private int GetPageAtScrollPosition()
{
  return textControl1.Lines.GetItem(
      new Point(0, textControl1.Height / 2)).Page;
}
[Visual Basic]
Private Function GetPageAtScrollPosition() As Integer
  Return textControl1.Lines.GetItem(New Point(0, textControl1.Height / 2)).Page
End Function

We just need to update the information using the VScroll event:

[C#]
private void textControl1_VScroll(object sender, EventArgs e)
{
  int iPageNumber = GetPageAtScrollPosition();
      Console.WriteLine("Page " +
      iPageNumber.ToString() +
      " of " +
      textControl1.Pages.ToString());

  Console.WriteLine("Section " +
      textControl1.GetPages()[iPageNumber].Section +
      " of " +
      textControl1.Sections.Count.ToString());
}
[Visual Basic]
Private Sub textControl1_VScroll(sender As Object, e As EventArgs)
  Dim iPageNumber As Integer = GetPageAtScrollPosition()
  Console.WriteLine("Page " +
      iPageNumber.ToString() +
      " of " +
      textControl1.Pages.ToString())

  Console.WriteLine("Section " +
      textControl1.GetPages()(iPageNumber).Section +
      " of " +
      textControl1.Sections.Count.ToString())
End Sub

<< Back