Hello...

I want to change the TextBox border color if certain event is true.

For example, in a GroupBox, there is a TextBox and a Button.

If the TextBox is empty, and I click the button,
I want the TextBox border color to change to red.

If the TextBox is not empty, I want the border color to remain unchanged.

How do I change the TextBox border color on a certain event?

Member Avatar for Unhnd_Exception

Use the Textbox's parent paint event to draw the border. You need to set the textbox's region to minus its border for it to show up.


The code will toggle a red border around a text box by pressing a button.

Its hard coded for a 3d border size

Private Sub GroupBox1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles GroupBox1.Paint

        'If the textbox's region hasn't been set then this will draw behind
        'the textbox.
        Dim p As New Pen(Color.Red, 2)
        e.Graphics.DrawRectangle(p, New Rectangle(TextBox1.Location + New Size(1, 1), TextBox1.Size - New Size(2, 2)))
        p.Dispose()

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Set the region to the textbox's size - its border size.
        If TextBox1.Region Is Nothing Then
            TextBox1.Region = New Region(New Rectangle(2, 2, TextBox1.Width - 4, TextBox1.Height - 4))
        Else
            TextBox1.Region = Nothing
        End If
     
    End Sub
commented: Thank you for the answer. +1

This code works perfect!

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.