A really useful custom label control with some built in features that makes our lives easier/cleaner
Basic features so far I have cooked up are:
- Wrap Text
- Success and Error Colors
In a "User Control" file (or class, but I think [And I am a bit rusty at the moment] you may have to modify this to work with a typical class file) add this code - Build your project and go to a Form and add the control from your toolbox.
Code:
Option Strict On
Imports System.Drawing
Imports System.Windows.Forms
Public Class WrapLabel
Inherits Control
Public Enum LabelType
Normal
Success
ErrorType
Custom
End Enum
Private _labelType As LabelType = LabelType.Normal
Public Property LabelStyle As LabelType
Get
Return _labelType
End Get
Set(value As LabelType)
_labelType = value
UpdateLabelStyle()
End Set
End Property
Private _text As String = String.Empty
Public Overrides Property Text As String
Get
Return _text
End Get
Set(value As String)
_text = value
UpdateLabelSize()
Invalidate()
End Set
End Property
Public Sub New()
SetStyle(ControlStyles.ResizeRedraw Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateLabelStyle()
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
MyBase.OnPaint(e)
Dim textFormat As New StringFormat()
textFormat.Alignment = StringAlignment.Near
textFormat.LineAlignment = StringAlignment.Near
textFormat.FormatFlags = StringFormatFlags.LineLimit
Dim textRect As RectangleF = New RectangleF(0, 0, Width, Height)
Dim textColor As Color = ForeColor
If _labelType = LabelType.Success Then
textColor = Color.Green
ElseIf _labelType = LabelType.ErrorType Then
textColor = Color.Red
End If
e.Graphics.DrawString(Text, Font, New SolidBrush(textColor), textRect, textFormat)
End Sub
Private Sub UpdateLabelStyle()
Dim textColor As Color = ForeColor
If _labelType = LabelType.Success Then
textColor = Color.Green
ElseIf _labelType = LabelType.ErrorType Then
textColor = Color.Red
End If
ForeColor = textColor
Invalidate()
End Sub
Private Sub UpdateLabelSize()
Dim newSize As Size = CalculatePreferredSize()
If newSize <> Size Then
Size = newSize
End If
End Sub
Private Function CalculatePreferredSize() As Size
Using g As Graphics = CreateGraphics()
Dim textFormat As New StringFormat()
textFormat.FormatFlags = StringFormatFlags.LineLimit
Dim proposedSize As New SizeF(Me.Width, Single.MaxValue)
Dim textSize As SizeF = g.MeasureString(Text, Font, proposedSize, textFormat)
Return New Size(CInt(Math.Ceiling(textSize.Width)), CInt(Math.Ceiling(textSize.Height)))
End Using
End Function
End Class
Ok... Now lets make the logic work:
Code:
Some IF THEN STATEMENT or mumbo jumbo
'Sucess
WrapLabel1.LabelStyle = WrapLabel.LabelType.Success
' Somethings wrong :blush: [Unfortunately we cannot just use "error] as this is a reserved word ]
Code:
WrapLabel1.LabelStyle = WrapLabel.LabelType.ErrorType
Everything is fairly straight forward easy to read and modify to your own liking e.g. you want shorter references or longer etc.