Grid controls are often used to display large quantities of data, which is often hard to read. One way to make the data in the grid more readable is to alternate the colors of the rows. A variety of custom controls will let you do this by selecting properties of the control without coding. However, when the budgets are tight, you can use a few lines of code to achieve the same effect with a regular grid control. Here’s a look at how you can alternate rows in the grid control to achieve this visual effect without having to purchase costly custom controls.
How does it work?
The technique relies on three subroutines that are called on the Form Load event: SetGridProperties, FillData, and ChangeRowColor.
SetGridProperties sets the properties of the grid control, specifying the number of rows and columns, setting the column headers, and stating the selection mode.
In FillData, we add data to the grid. Normally, you would have the data coming from either a database or a file, but for the example, we’ll just hard code sample data.
ChangeRowColor handles the whole background color modification. Notice that the function accepts one parameter (bSelected as Boolean). We use this to distinguish between the first time the control is shown and the time when we “repaint” the control after a user has clicked on a cell. On the Form Load event, we call this function, passing False value to bSelected.
In ChangeRowColor, we go through all the rows the grid control has and check to see whether the remainder from the division of i (row number) by 2 is 0 (the number is even). If the number is even, we change the background color of the cell to cyan (vbCyan); if the number is odd, we change the background to white (vbWhite). Since we have to do this for every column of the particular row, we have a loop inside the loop to go through all the columns. Listing A shows the code.
When a user clicks on a grid cell, we want the whole row to change to an alternative color. First, set the redraw property of the grid to False (to avoid flickering of the screen) and call the ChangeRowColor routine again—but this time pass True for bSelected. In ChangeRowColor, if bSelected is True, we get the value of the row that’s currently selected by the user and change its background color to a different color. In this case, we use system color vbMenuBar. Once this is done, set the grid’s redraw property back to True.
When you run the sample project, notice that the row colors are alternated between white and cyan. Click on any cell and the whole row will change color.
Download the code included in this article
Let highlighting work for you
In the example here, we used a small grid to demonstrate a simple way of alternating grid control’s row colors. In real life applications, where you’re displaying large quantities of data, this trick will make it easier for users to keep track of which row they are looking at.