Search code examples
vb.netcolorsborderpanel

VB.Net - Change the Panel's Border color


I searched in stack overflow something like this "How to change Panel's border color vb.net" and no results found so, I removed the vb.net and just typed like that and I found results but it is for C# only and I don't C# that much better and maybe I thought I could translate but I just thought translating will not be 100% Accurate so, that's why I made this question. Please help me how do I change the Panel's border Color in VB.Net I've set the BorderStyle FixedSingle in properties but there is still nothing I can do to change the Panel's border color. Please help and tell me how to change the Panel's border color or we can't do it from properties and we can do it by coding then at least please give me the code.


Solution

  • As you already mentioned, there's a c# version of this question with multiple answers.

    Here's a short summary of the answers:

    Possibility 1

    The simplest and codeless way is as follows:

    • Set the BackColor of Panel1 to the desired bordercolor
    • Set the Padding of Panel1 to the desired border-thickness (e.g. 2;2;2;2)
    • Create a Panel2 inside Panel1 and set the Dock-property to Fill
    • Set the BackColorof Panel2 to the desired background color

    Caveat: Transparent background can not be used.

    Possibility 2

    Draw a Border inside the Paint event-handler.
    (Translated to VB.NET from this answer.)

    Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
        ControlPaint.DrawBorder(e.Graphics, Panel1.ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid)
    End Sub
    

    Possibility 3

    Create your own Panel-class and draw the border in the client area.
    (Translated to VB.NET from this answer.)

    <System.ComponentModel.DesignerCategory("Code")>
    Public Class MyPanel
        Inherits Panel
    
        Public Sub New()
            SetStyle(ControlStyles.UserPaint Or ControlStyles.ResizeRedraw Or ControlStyles.DoubleBuffer Or ControlStyles.AllPaintingInWmPaint, True)
        End Sub
    
        Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            Using brush As SolidBrush = New SolidBrush(BackColor)
                e.Graphics.FillRectangle(brush, ClientRectangle)
            End Using
    
            e.Graphics.DrawRectangle(Pens.Yellow, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1)
        End Sub
    End Class