Search code examples
listviewvb.net-2010

How to change the color of a cell(back or fore color) of listview item according to item value


How to change the color of a cell(back or fore color) of listview item according to item value with if condition.

I do it but it is not work(means not change the color but showing the massage) and show no error, Debug to step through the code line by line and check the values of controls and variables Please help me......

Private Sub btnaddcat_Click(ByVal sender As System.Object, ByVal e As For k = 0 To ListView1.Items.Count - 1
If ListView1.Items(k).SubItems(6).Text > 100 Then
ListView1.Items(k).SubItems(6).ForeColor = System.Drawing.Color.Red
MsgBox("hi test code yes")
Else
MsgBox("hi test code no")
End If
Next k
    End Sub

Solution

  • I think you have do it in ItemDataBound event. It's will do your code automatically for each row during data binding in listview.

    Example:

    Private Sub listViewName_DataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles listViewName.ItemDataBound
    
        'Add your condition for change color here
        If e.Items.SubItems(6).Text > 100 Then
            e.Items.SubItems(6).ForeColor = Color.Red
        Else
            e.Items.SubItems(6).ForeColor = Color.Blue
        End If
    
    End Sub