Search code examples
vb.netgraphicsdrawrectangle

Draw rectangle around Textbox inside a Groupbox


I want to add a custom border around a TextBox control which is in a GroupBox. Since I'm new to this Graphic stuff I'm having a hard time figuring out the problem.

This is the code i'm using:

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint

    Dim _g As Graphics = Me.GroupBox1.CreateGraphics
    Dim pen As New Pen(Color.Red, 2.0)
    _g.DrawRectangle(pen, New Rectangle(TextBox1.Location, TextBox1.Size))
    pen.Dispose()

End Sub

This form is a secondary form that shows when I click on a button from the Main form. The Red Border appears for a second when the form loads and then disappears.


Solution

  • You need to handle the GroupBox paint event, not the form.

    Private Sub HandleGroupBox1Paint(sender As Object, e As PaintEventArgs) Handles GroupBox1.Paint
        Using p As New Pen(Color.Red, 2.0)
            e.Graphics.DrawRectangle(p, Me.TextBox1.bound)
        End Using
    End Sub