Change the background color of individual columns

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.



To set the background color of a column, the list view control has to be owner drawn. In an owner drawn control, each row is drawn by the application program rather than by the control. So when drawing a row, the background color can be set to our choice within the rectangle occupied by a particular column. To implement an owner drawn control
see the topic ‘Selection highlighting of entire row’.

The code segment below illustrates how to set yellow as the background color for alternate columns. The code shown is part of the DrawItem() function. The first segment draws the background color just before drawing the state icon. The second segment draws the background color within the loop that draws the labels for the remaining columns.

	// Set clip region
	rcCol.right = rcCol.left + GetColumnWidth(0);
	CRgn rgn;
	rgn.CreateRectRgnIndirect(&rcCol);
	pDC->SelectClipRgn(&rgn);
	rgn.DeleteObject();

	// Draw column background
	if( !bHighlight )
		pDC->FillRect(rcCol, &CBrush(RGB(255,255,0)));

	// Draw state icon
	if (lvi.state & LVIS_STATEIMAGEMASK)

	:
	:
	:
	:

	for(int nColumn = 1; GetColumn(nColumn, &lvc); nColumn++)
	{
		rcCol.left = rcCol.right;
		rcCol.right += lvc.cx;

		// Draw column background
		if( !bHighlight || ( bHighlight && m_nHighlight == HIGHLIGHT_NORMAL ) )
			if( (nColumn+1) % 2 )
				pDC->FillRect(rcCol, &CBrush(RGB(255,255,0)));


 

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read