Listview用自定义颜色vb.net突出显示所选项目

时间:2018-07-21 01:02:51

标签: vb.net listview highlight

以下例程有助于在VB.Net中突出显示具有自定义颜色的列表视图所选项目。在代码模块中具有以下代码,传递列表视图和所需的颜色,以使选定的项目以给定的颜色突出显示。

Public Sub ListViewHighLightSelectedItem(oListView As ListView, clrHighLightColor As System.Drawing.Color)
    Try
        If oListView.SelectedItems.Count > 0 Then
            For Each oLVItem As ListViewItem In oListView.Items
                oLVItem.UseItemStyleForSubItems = False
                If oLVItem.Selected = True Then
                    'Selected item
                    For Each oSubItem In oLVItem.SubItems
                        oSubItem.BackColor = clrHighLightColor
                    Next
                Else
                    'Non selected item
                    For Each oSubItem In oLVItem.SubItems
                        oSubItem.ResetStyle()
                    Next
                End If
            Next
        End If
    Catch ex As Exception
        'Have your exception handling code here!
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

我不确定是什么问题,但是我基于您的代码。只是将For循环更改为仅选定的项目。另外,我没有通过列表视图。仅当代码不在表单类中或您具有多个listview时才需要这样做。我还在设计时将FullRowSelect更改为true。

Private Sub OpCode(clrHighLightColor As System.Drawing.Color)
        Try
            If ListView1.SelectedItems.Count = 0 Then Return
            For Each lvi As ListViewItem In ListView1.SelectedItems
                lvi.BackColor = clrHighLightColor
            Next
        Catch ex As Exception
            'Have your exception handling code here!
        End Try
    End Sub
    Private Sub btnChangeLVBackColor_Click(sender As Object, e As EventArgs) Handles btnChangeLVBackColor.Click
        Dim myColor As Color = Color.Red
        OpCode(myColor)
    End Sub