# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  VB - Color a row in a ListView

## MartinLiss

This sub when called will color a ListView row.

VB Code:
Public Sub ColorListviewRow(lv As ListView, RowNbr As Long, RowColor As OLE_COLOR)
'***************************************************************************
'Purpose: Color a ListView Row
'Inputs : lv - The ListView
'         RowNbr - The index of the row to be colored
'         RowColor - The color to color it
'Outputs: None
'***************************************************************************
    
    Dim itmX As ListItem
    Dim lvSI As ListSubItem
    Dim intIndex As Integer
    
    On Error GoTo ErrorRoutine
    
    Set itmX = lv.ListItems(RowNbr)
    itmX.ForeColor = RowColor
    For intIndex = 1 To lv.ColumnHeaders.Count - 1
        Set lvSI = itmX.ListSubItems(intIndex)
        lvSI.ForeColor = RowColor
    Next
     Set itmX = Nothing
    Set lvSI = Nothing
    
    Exit Sub
 ErrorRoutine:
     MsgBox Err.Description
 End Sub
Usage: (To make the 5th row of a ListView Red)

ColorListviewRow MyListView, 5, vbRed

----------


## MartinLiss

It has been pointed out that when using vbBlue as the color, only the first column gets colored! Why that should be I have no idea, but you can get around the problem by using 16711681 instead of vbBlue (which is 16711680).

----------


## DJ1234

when I tried with this code, the first row is not getting colored. All other rows have the specific color mentioned in the code.

Please let me know how can I color the first row.

----------


## MartinLiss

Welcome to VB Forums!

I assume what you mean is that the first column of the first row is getting colored, but not the 2nd, 3rd, etc columns of the first row. If that's the case then add the following because it seems that that row doesn't color until it gets focus.


VB Code:
Public Sub ColorListviewRow(lv As ListView, RowNbr As Long, RowColor As OLE_COLOR)
'***************************************************************************
'Purpose: Color a ListView Row
'Inputs : lv - The ListView
'         RowNbr - The index of the row to be colored
'         RowColor - The color to color it
'Outputs: None
'***************************************************************************
    
    Dim itmX As ListItem
    Dim lvSI As ListSubItem
    Dim intIndex As Integer
    
    On Error GoTo ErrorRoutine
    
    Set itmX = lv.ListItems(RowNbr)
    itmX.ForeColor = RowColor
    For intIndex = 1 To lv.ColumnHeaders.Count - 1
        Set lvSI = itmX.ListSubItems(intIndex)
        lvSI.ForeColor = RowColor
        DoEvents
    Next
    [HL="#FFFF80"]lv.ListItems(2).Selected = True
    lv.ListItems(1).Selected = True[/HL]
     Set itmX = Nothing
    Set lvSI = Nothing
    
    Exit Sub
 ErrorRoutine:
     MsgBox Err.Description
 End Sub

----------


## dinosaur_uk

Is it possible to colour the first Column and second column programatically?

----------


## MartinLiss

This will do it.



```
Public Sub ColorListviewColumns(lv As ListView, ColumnNumber As Long, ColumnColor As OLE_COLOR)
'***************************************************************************
'Purpose: Color a ListView Row
'Inputs : lv - The ListView
'         ColumnNumber - The index of the row to be colored
'         ColumnColor - The color to color it
'Outputs:
'***************************************************************************
    
    Dim itmX As ListItem
    Dim lvSI As ListSubItem
    Dim intIndex As Integer
    Dim intRow As Integer
    
    On Error GoTo ErrorRoutine
    
    For intRow = 1 To lv.ListItems.Count
        Set itmX = lv.ListItems(intRow)
        itmX.ForeColor = ColumnColor
        Set lvSI = itmX.ListSubItems(ColumnNumber - 1)
        lvSI.ForeColor = ColumnColor
    Next

    lv.ListItems(ColumnNumber).Selected = True
    
    Set itmX = Nothing
    Set lvSI = Nothing
    
    lv.Refresh
    
    Exit Sub

ErrorRoutine:

    MsgBox Err.Description

End Sub
```

Usage



```
ColorListviewColumns MyListView, 2, vbRed '
```

The column headers themselves won't be colored.

----------


## akhileshbc

I made some changes to *Marty* 's code, so that it can make dual colors for the rows in ListView...


```
Public Sub ColorListviewRow(lv As ListView, Color1 As OLE_COLOR, Color2 As OLE_COLOR)
        
Dim itmX As ListItem
Dim lvSI As ListSubItem
Dim intIndex As Integer, i As Integer
         
On Error GoTo ErrorRoutine
For i = 1 To lv.ListItems.Count
    If (i Mod 2) = 0 Then
        Set itmX = lv.ListItems(i)
        itmX.ForeColor = Color2
        For intIndex = 1 To lv.ColumnHeaders.Count - 1
            Set lvSI = itmX.ListSubItems(intIndex)
            lvSI.ForeColor = Color2
            DoEvents
        Next
        lv.ListItems(i).Selected = True
    Else
        Set itmX = lv.ListItems(i)
        itmX.ForeColor = Color1
        For intIndex = 1 To lv.ColumnHeaders.Count - 1
            Set lvSI = itmX.ListSubItems(intIndex)
            lvSI.ForeColor = Color1
            DoEvents
        Next
        lv.ListItems(i).Selected = True
    End If
Next
Set itmX = Nothing
Set lvSI = Nothing
Exit Sub

ErrorRoutine:
    MsgBox Err.Description
End Sub
```

Example usage:


```
ColorListviewRow ListView1, vbGreen, vbRed
```

Example output:

abc def ghi jkl mno pqr stu vwx yz
abc def ghi jkl mno pqr stu vwx yz
abc def ghi jkl mno pqr stu vwx yz
abc def ghi jkl mno pqr stu vwx yz
abc def ghi jkl mno pqr stu vwx yz
......

----------


## Condomx

can someone give me a specific little tutorial on how to apply this please.

----------


## akhileshbc

> can someone give me a specific little tutorial on how to apply this please.


Sample usage is provided at the end of each piece of code....  :wave: 
You have to pass your Listview's name and the color required....

----------


## Condomx

I mean,what should i put to the load event when calling it.?

----------


## MartinLiss

Call what? You don't need to put anything into Form_Load. All you need is the code behind the "Color Row 5" button and the ColorListviewRow sub.

----------


## Condomx

oh ok,i though you need to call that public sub so that it will work.

----------


## Eliminator2009

When a use clicks on a row or column the column or row must be HiLighted to any color.

is it possible ?

----------


## akhileshbc

> When a use clicks on a row or column the column or row must be HiLighted to any color.
> 
> is it possible ?


Try this:


```
Option Explicit

Private Sub Form_Load()
    '~~~ Adding some text for testing purpose (create two column headers in design time)
    Dim i As Long
    For i = 1 To 50
        ListView1.ListItems.Add , , i
        ListView1.ListItems(i).SubItems(1) = i
    Next
End Sub

'~~~ When we click on it
Private Sub ListView1_Click()
    ColorListviewRow ListView1, ListView1.SelectedItem.Index, vbRed '~~~ We are passing the Listview's name, selected item's index and the color to the sub
End Sub

'~~~ Sub for coloring
Public Sub ColorListviewRow(lv As ListView, sel_Item As Long, Color1 As OLE_COLOR)
 
    Dim itmX        As ListItem
    Dim lvSI        As ListSubItem
    Dim intIndex    As Integer, i As Integer
         
    On Error GoTo ErrorRoutine
    Set itmX = lv.ListItems(sel_Item)
    itmX.ForeColor = Color1
    For intIndex = 1 To lv.ColumnHeaders.Count - 1  '~~~ Coloring the full row with the selected color
        Set lvSI = itmX.ListSubItems(intIndex)
        lvSI.ForeColor = Color1
        DoEvents
    Next
    Set itmX = Nothing
    Set lvSI = Nothing
    Exit Sub
    
ErrorRoutine:
    MsgBox Err.Description
End Sub
```

..... :wave:

----------


## JamieWarren09

Hey Everyone, Sorry to bring up a post in a topic that's not new!

But was wondering for some help!

I currently have 1 listview boxes  and users can move the selected item from one listbox to the other.

i want it so when the user moves one item from listview1 to listview2 then the selected item they moved will be colored...


heres my code to move items from listview1 to listview2 



```
Dim ListObj3 As ListItem 'Set listObj as a listitem
Set ListObj3 = playlist.ListView1.ListItems.Add(, , ListView3.SelectedItem.Text)
ListObj3.SubItems(3) = ListView3.SelectedItem.SubItems(3)
ListObj3.SubItems(4) = ListView3.SelectedItem.SubItems(4)
```

Which works fine!

How ever what can i change in this



```
ColorListviewRow playlist.ListView1, 5, vbRed
```

so that rather than the (5th line) be colored, its just the selected item they moved that gets colored red?

Thanks,
Jamie

----------


## akhileshbc

Since the newly added item will be appended as a new item at the end of second ListView, you could try something like this:


```
ColorListviewRow playlist.ListView1, playlist.ListView1.ListItems.Count, vbRed
```

_I didn't tested it._

 :wave:

----------


## JamieWarren09

Hey Mate,
That works! 

Thanks,
However i am now getting a error saying ' Index out of bounds' i then press OK, and it still colors the thing as i wanted!

is there a way to trap that error, and ignore it? 

i tried on error resume next,
how ever it still comes up!!

----------


## akhileshbc

Can you show us the code ?

 :wave:

----------


## lllllsp1d3rlllll

thats cool that ppl are learning simple things like adding color to a listview node

----------


## uzzeierrll

Hi Martin,

Can you help me? How to color each list items in my listview that connected to my database?
I have a code here that display in my listview the available room and not available room for the day. I want the available room to be in forecolor blue and not available room to be in red forecolor. 

CODE:
Private Sub Form_Load()
Dim romarray() As Integer
Dim icounter As Integer
Dim romlength As Integer

icounter = 0

conn
RS.Open "SELECT * FROM room", CON, 3, 3

    ReDim romarray(0 To RS.RecordCount - 1) As Integer

    Do Until RS.EOF
        romarray(icounter) = RS("roomNO")
        icounter = icounter + 1
        RS.MoveNext
    Loop

RS.Close
CON.Close


For romlength = LBound(romarray) To UBound(romarray)
    conn
    RS.Open "SELECT * FROM room, availability WHERE availability.roomNO = '" & romarray(romlength) & "' AND availability.status_date = '" & Format(Date) & "' AND availability.roomNo=room.roomNo", CON, 3, 3

        If RS.RecordCount = 1 Then
            With viewall.ListItems.Add(, , romarray(romlength))    ------>not available room
                .SubItems(1) = RS("room_status")
             End With

        ElseIf RS.RecordCount = 0 Then
            viewall.ListItems.Add , , romarray(romlength)   ------>available room
        End If

    RS.Close
    CON.Close
Next romlength
End Sub
----------------------------------------------
SAMPLE OUTPUT:
101    Reserved  
102    Available
103    Available
----------------------------------------------

Help me please..i really need it..thanks a lot..

----------


## Smartchap

Hey Jammie

You are getting error "Index out of bounds" because you are using ListView1 in line
ColorListviewRow playlist.ListView1, playlist.ListView1.ListItems.Count, vbRed

Try using ListView2 as
ColorListviewRow playlist.ListView2, playlist.ListView2.ListItems.Count, vbRed

----------


## Smartchap

Dear uzzeierrll

Can you post your code with database file,etc so that I could help you.

----------


## Smartchap

I tried Martin's code but in some rows it colours only 2-3 items, in some rows 3-4 items and in rows all items, whereas we requires each item to be coloured as required for the clicked row.

For everyone, I found a good solution at this site / thread:

http://forums.devx.com/showthread.php?t=169151

it colours each item of any clicked row in a listview to blue (you can change the colour). Thanks to Lennie (on that forum).

----------


## JamieWarren09

Hi Martin, Is it possible to make this code color subitems(3)

and if subitems(3) contains 'high' then it automatically color to red? as apose to the whole column being colored red?

Thanks
Jamie

----------


## MartinLiss

Sure. Modify this part of my original code.



```
Set itmX = lv.ListItems(RowNbr)
    'itmX.ForeColor = RowColor
    'For intIndex = 1 To lv.ColumnHeaders.Count - 1
        If itmX.ListSubItems(3).Text = "high" Then ' Im not sure that Text is correct but you get the idea
            Set lvSI = itmX.ListSubItems(3)
            lvSI.ForeColor = RowColor
            DoEvents
        End If
    'Next
```

----------


## herrmlm

How can you change the font color of a row in your ListView when the row is selected?  The blue highlight changes the font color back to white.  Thanks!

----------


## fafalone

It should be noted that this code can only be used with VB's Microsoft Windows Common Controls 6.0 (mscomctl instead of comctl32), which some people don't use for various reasons. Of course one advantage is that the coloring can be done without subclassing; using NM_CUSTOMDRAW would be required with 5.0.

(PS- A question is, will this color the background of a subitem image?)

If you had a subclassed 5.0 ListView, in its WndProc you'd do it like this:


```
Select Case uMsg
    Case OCM_NOTIFY
        Dim tNMH As NMHDR
        CopyMemory tNMH, ByVal lParam, Len(tNMH)
  

        Select Case tNMH.Code

            Case NM_CUSTOMDRAW
                Dim NMLVCD As NMLVCUSTOMDRAW
                CopyMemory NMLVCD, ByVal lParam, Len(NMLVCD)
                With NMLVCD.NMCD
                    Select Case .dwDrawStage

                        Case CDDS_PREPAINT
                            LVWndProc = CDRF_NOTIFYITEMDRAW
                            Exit Function

                        Case CDDS_ITEMPREPAINT
                            LVWndProc = CDRF_NOTIFYSUBITEMDRAW
                            Exit Function

                        Case CDDS_ITEMPREPAINT Or CDDS_SUBITEM
                                    
                            NMLVCD.ClrText = TEXTCOLOR
                            NMLVCD.ClrTextBk = BACKGROUNDCOLOR
                            CopyMemory ByVal lParam, NMLVCD, Len(NMLVCD)

                            LVWndProc = CDRF_NOTIFYSUBITEMDRAW
                            Exit Function

                    End Select
                End With
            End Select
End Select
```

This isn't the complete code to do it, it's just what you'd add if you were already using a 5.0 ListView AND had it subclassed.
If you wanted to make an item/subitem bold, you'd use SelectObject NMLVCD.NMCD.hDC, hFont_Bold (where hFont_Bold is a valid hFont; obviously you can change it to any font you want, Bold is just the most common use, also italics, different face; any font).

----------

