开发者

Visual Basic .NET - Change color of one listBox item

开发者 https://www.devze.com 2023-02-15 12:05 出处:网络
I\'m making a small program in VB.NET. I have a listBox and a button. I\'d like to be able to press the button and have the selected listBox item change it\'s foreColor to green. I\'ve tried many ways

I'm making a small program in VB.NET. I have a listBox and a button. I'd like to be able to press the button and have the selected listBox item change it's foreColor to green. I've tried many ways of doing this, ranging from overriding the draw method to using a listView (listBox is much better for what I'm doing, please don't recommend that I use a listView, I've already tried it.)

At first I thought this would be simple, but it's the exact opposite and I'm very frustrated that such a simple task should be so difficult. I don't want to use any third-party controls, a开发者_如何学编程s I'd have to completely re-write my application.

I've tried so many different options it's not even funny. Please, can anyone offer a simpler solution?

-Q


You need to handle DrawItem event and DrawMode=OwnerDrawFixed property.

Dim buttonPressed As Boolean
Private Sub ListBox1_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
    e.DrawBackground()

    If ListBox1.SelectedIndices.Contains(e.Index) And buttonPressed Then
        e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Green, e.Bounds.X, e.Bounds.Y)

    Else
        e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y)
    End If
    If e.Index = ListBox1.Items.Count - 1 Then
        buttonPressed = False
    End If
    e.DrawFocusRectangle()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    buttonPressed = True
    ListBox1.Refresh()
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号