Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

vb.net - Dynamically changing a listbox line using VIsual Basic 2015

I was wondering if it is possible to change lines in a Listbox that have only a certain character in it. For example I have a list of names. I am using Visual Basic 2015

Joe
John
Mike
*Steve
*Tim
Michelle

I would like to make the ones that have the *(or any special character) turn the line Red. I can hard wire in the code exact matches and make it turn red but my listbox will have dynamic information in it so it will be changing all the time. I am marking the information I would like to highlight the information that has the *. Thank you for your time. Here is a small snipet of the generic code I was trying to use.

    If ListBox1.Items(e.Index).ToString() = "red.txt" Then
        e.Graphics.FillRectangle(Brushes.red, e.Bounds)
    End If

    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Handle the DrawItem event and paint each item yourself. You must have ListBox1.DrawMode = DrawMode.OwnerDrawFixed

Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
    Dim s As ListBox = CType(sender, ListBox)
    If e.Index < 0 Then Exit Sub
    Dim t = s.Items(e.Index).ToString()
    Using g = e.Graphics
        e.DrawBackground()
        If t.Contains("*"c) Then ' your custom condition
            g.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
        End If
        g.DrawString(t, e.Font, New SolidBrush(e.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))
        e.DrawFocusRectangle()
    End Using
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.DrawMode = DrawMode.OwnerDrawFixed
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...