Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleShow and hide TextBox scroll bars as needed in Visual Basic 2005
DescriptionThis example shows how to show and hide TextBox scroll bars as needed in Visual Basic 2005.
KeywordsTextBox, scroll bar
CategoriesControls
 
Subroutine CheckScrollBars displays or hides a TextBox's vertical scroll bar depending on whether it is big enough to hold its text. The code makes a Graphics object associated with the TextBox. It makes a layout area that fills the TextBox and calls the Graphics object's MeasureString method to see how much of the control's text will fit. If the text won't all fit, the program displays the TextBox's vertical scroll bar.
 
' See if the TextBox needs a vertical scroll bar.
Private Sub CheckScrollBars(ByVal txt As TextBox)
    ' Make a Graphics object for the TextBox.
    Dim gr As Graphics
    gr = txt.CreateGraphics()

    ' Make a layout rectangle.
    Dim layout_area As New SizeF(txt.ClientSize.Width, _
        txt.ClientSize.Height)
    Using sf As New StringFormat()
        Dim chars_fitted, lines_filled As Integer
        gr.MeasureString(txt.Text, txt.Font, layout_area, _
            sf, chars_fitted, lines_filled)

        ' See if all characters fitted.
        If chars_fitted < txt.Text.Length Then
            txt.ScrollBars = ScrollBars.Vertical
        Else
            txt.ScrollBars = ScrollBars.None
        End If
    End Using
End Sub
 
The example program checks its TextBox whenever its text changes or it is resized.
 
Private Sub txtTest_Resize(ByVal sender As Object, ByVal e _
    As System.EventArgs) Handles txtTest.Resize
    CheckScrollBars(txtTest)
End Sub

Private Sub txtTest_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    txtTest.TextChanged
    CheckScrollBars(txtTest)
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated