
Introduction
This article describes how to create a custom vertical label user control in VB.NET.
Working
Create a new Windows user control. Change the inherited class from System.Windows.Forms.UserControl
to System.Windows.Forms.Control
. Add an icon file in the project to associate with the control and set its property to "EmbeddedResource
" and add a class attribute <ToolboxBitmap(GetType(Name of Class), "Name of Icon file")
. Delete:
components = New System.ComponentModel.Container()
line in the Windows designer generated code and add the default size of the label. For example:
Me.Size = New System.Drawing.Size(24, 100)
Override the OnPaint
method and the Text
property of the control. Build the control and add it to your toolbox.
Source Code
Imports System.ComponentModel
<ToolboxBitmap(GetType(VerticalLabel), "Varticallabel.ico")> _
Public Class VerticalLabel
Inherits System.Windows.Forms.Control
Private labelText As String
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ComponentModel.Container
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Size = New System.Drawing.Size(24, 100)
End Sub
#End Region
Protected Overrides Sub OnPaint(ByVal e As _
System.Windows.Forms.PaintEventArgs)
Dim sngControlWidth As Single
Dim sngControlHeight As Single
Dim sngTransformX As Single
Dim sngTransformY As Single
Dim labelColor As Color
Dim labelBorderPen As New Pen(labelColor, 0)
Dim labelBackColorBrush As New SolidBrush(labelColor)
Dim labelForeColorBrush As New SolidBrush(MyBase.ForeColor)
MyBase.OnPaint(e)
sngControlWidth = Me.Size.Width
sngControlHeight = Me.Size.Height
e.Graphics.DrawRectangle(labelBorderPen, 0, 0, _
sngControlWidth, sngControlHeight)
e.Graphics.FillRectangle(labelBackColorBrush, 0, _
0, sngControlWidth, sngControlHeight)
sngTransformX = 0
sngTransformY = sngControlHeight
e.Graphics.TranslateTransform(sngTransformX, _
sngTransformY)
e.Graphics.RotateTransform(270)
e.Graphics.DrawString(labelText, Font, _
labelForeColorBrush, 0, 0)
End Sub
Private Sub VTextBox_Resize(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Resize
Invalidate()
End Sub
<Category("Verticallabel"), _
Description("Text is displayed vertiaclly in container")> _
Public Overrides Property Text() As String
Get
Return labelText
End Get
Set(ByVal Value As String)
labelText = Value
Invalidate()
End Set
End Property
End Class