Search code examples
vb.nettextbox

Is it possible to create a dashed border around text boxes in visual basic.net windows form application?


I've been working with a code that allows me to draw lines around text boxes in vb.net but these lines are solid lines. I'd like to have dashed or even dotted lines to dress the application up a little. Is there a way to make dashed lines around text boxes like you can do on the form? The current code I'm using is as so..

Dim g As Graphics = e.Graphics
Dim pen As New Pen(Color.Aqua, 2.0)
Dim txtBox As Control
  For Each txtBox In Me.Controls
      If TypeOf (txtBox) Is TextBox Then
          g.DrawRectangle(pen, New Rectangle(txtBox.Location, txtBox.Size))
      End If
  Next
pen.Dispose()

I wanted to also mention I am able to used this code in the paint event to get a dashed line around my form. It would look really nice to get it around the text boxes too I hope this is possible!

ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,Color.Aqua, ButtonBorderStyle.Dashed)

EDIT: I've just tried this code it seems to be drawing dashed rectangles but they are not going around my textboxes so not sure how to fix it.

Dim txtBox As Control
  For Each txtBox In Me.Controls
    If TypeOf (txtBox) Is TextBox Then
      ControlPaint.DrawBorder(e.Graphics, txtBox.ClientRectangle, txtBox.ForeColor, ButtonBorderStyle.Dashed)
    End If
  Next

Solution

  • like this

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        For Each txtBox As Control In Me.Controls
            If TypeOf (txtBox) Is TextBox Then
                Dim borderRectangle As Rectangle = New Rectangle(txtBox.Location, txtBox.Size)
                borderRectangle.Inflate(1, 1)
                ControlPaint.DrawBorder(e.Graphics, borderRectangle, txtBox.ForeColor, ButtonBorderStyle.Dashed)
            End If
        Next
    End Sub