Thursday, 13 August 2015

How to Set background color of Combobox item in vb.net


'Set the Combobox's DrawMode property to OwnerDrawVariable

    Private Sub test_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim ColorName As String
        For Each ColorName In System.Enum.GetNames(GetType(System.Drawing.KnownColor))
            ComboBox1.Items.Add(Color.FromName(ColorName))
        Next
    End Sub
    'The above code will load the known color names, and then adds Color objects to the combobox's Items collection.
    'Next, let's add our MeasureItem sub ( for the combobox ) :
    Protected Sub Combobox1_MeasureItem(ByVal sender As Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles ComboBox1.MeasureItem
        Dim myRandom As New Random
        e.ItemHeight = myRandom.Next(20, 20)
    End Sub
    'This, will call the overloaded Random.Next method to get the next random number between 20 and 40, and assign that to the ItemHeight property of the MeasureItemEventArgs parameter.
    'Last step, add the DrawItem event :
    Protected Sub Combobox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
        If e.Index < 0 Then
            e.DrawBackground()
            e.DrawFocusRectangle()
            Exit Sub
        End If
        ' Get the Color object from the Items list
        Dim CurrentColor As Color = CType(ComboBox1.Items(e.Index), Color)

        ' get a square using the bounds height
        Dim SizeRect As Rectangle = New Rectangle(2, e.Bounds.Top + 2, e.Bounds.Width, e.Bounds.Height - 2)

        Dim ComboBrush As Brush

        ' call these methods first
        e.DrawBackground()
        e.DrawFocusRectangle()

        ' change brush color if item is selected
        If e.State = Windows.Forms.DrawItemState.Selected Then
            ComboBrush = Brushes.White
        Else
            ComboBrush = Brushes.Black
        End If

        ' draw a rectangle and fill it
        e.Graphics.DrawRectangle(New Pen(CurrentColor), SizeRect)
        e.Graphics.FillRectangle(New SolidBrush(CurrentColor), SizeRect)

        ' draw a border
        SizeRect.Inflate(1, 1)
        e.Graphics.DrawRectangle(Pens.Black, SizeRect)

        ' draw the Color name
        e.Graphics.DrawString(CurrentColor.Name, ComboBox1.Font, ComboBrush, e.Bounds.Height + 5, ((e.Bounds.Height - ComboBox1.Font.Height) \ 2) + e.Bounds.Top)
    End Sub







No comments:

Post a Comment