Introduction
This article provides code to get only the viewable text from
a textbox. This is useful in case we want to display part of the text which is not
viewable on other screens using controls like richtextbox or any other text displaying controls.
Background
This code was developed because of a unique requirement while displaying reports in
a project. In the reports there was a textarea for Narration having width = 285 and height=250. So when
the user was entering a long text, the RDLC textarea used to clip off the textarea after
a specific number of characters. The decision was made to display the remaining text on
a supplement report. The challenge was to find the exact number of characters displayed on
an RDLC textarea.
To overcome this situation I came up with a solution to have a textbox in runtime have all
the same dimensions as that of a textarea in an RDLC report, like font, size, and has
the following code to serve the purpose.
The below function accepts two parameters:
- Textbox which you need to get the viewable text from
- Number of viewable lines
Private Function GetViewableTextFromTextbox(ByVal textbox As _
TextBox, ByVal textboxLines As Int32) As String
Dim prevLineNumber As Integer = 1
Dim currentLineNumber As Integer = 1
Dim totalLines As Integer = 1
Dim visibleText As String = String.Empty
For charIndex = 0 To textbox.Text.Length - 1
visibleText = textbox.Text.Substring(0, charIndex)
Dim renderedTxtboxPoint As Point
renderedTxtboxPoint = textbox.GetPositionFromCharIndex(charIndex)
currentLineNumber = renderedTxtboxPoint.Y
If prevLineNumber <> currentLineNumber Then
prevLineNumber = currentLineNumber
totalLines += 1
If totalLines > textboxLines Then
GetViewableTextFromTextbox = visibleText
Exit For
End If
End If
Next
GetViewableTextFromTextbox = visibleText
End Function
To get the viewable text for your textbox, call it as below:
GetVisibleTextFromTextbox(Textbox1, 18)