.NET Discussion

.NET Issues, Problems, Code Samples, and Fixes

How To Color Code Your DataGrid/GridView/DataGridView

While working on my product hit tracking system, I had the idea of color coding my results based on the URL they were referred from.  Once I got started, I realized that it was easier than I thought. The solution is pretty straightforward, but I assume that it will help someone out who is looking for a way to manipulate data based on string content. 

Basically, before you bind your data to your datagrid/gridview/datagridview, cycle through all your records in search of a string. For instance, I searched for “google”, “yahoo”, and “msn.com” and subsequently surrounded that data with a respective “<span class=”google”>” or yahoo or msn.  The code is easy:

Dim dv As DataView = GetData(SQL) 'populate your dataview however you do it
  Dim row As DataRowView
  Dim i As Integer
  Dim cols As Integer = dv.Table.Columns.Count 'get the number of columns in your dataview
  For Each row In dv
   For i = 0 To cols - 1 'go through each cell and color code as necessary
    If InStr(row(i).ToString, "google") Then 'search for the term "google"
     row.BeginEdit()
     row(i) = "<span class='google'>" & row(i) & "</span>"
     row.EndEdit()
   ElseIf InStr(row(i).ToString, "yahoo") Then 'search for the term "yahoo"
     row.BeginEdit()
     row(i) = "<span class='yahoo'>" & row(i) & "</span>"
     row.EndEdit()
    ElseIf InStr(row(i).ToString, "msn.com") Then 'search for the term "msn.com"
     row.BeginEdit()
     row(i) = "<span class='msn'>" & row(i) & "</span>"
     row.EndEdit()
    End If
   Next
  Next

Then in your CSS stylesheet you define classes for .google, .yahoo, and .msn.  Easy! This technique can be applied to anything you want to do with the string value of each cell in your data set.

Anyone have a cool algorithm that does something similar to this? Please share!

EDIT (10/30/2007):

Today I was trying to use this technique, but hit a snag because my datasource was bound to a Generics list (ie, List(of T)), so I found another way to do it. It’s possible to use the RowDataBound event to iterate through the rows and cells to find what you need. Here’s an example that works for me:

Protected Sub gvExisting_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
 	'8 is where inventory is kept, "stock" is the header text
 	If e.Row.Cells(8).Text &lt;> "0" And e.Row.Cells(8).Text &lt;> "Stock" Then  
	Dim str As String = "<span>" & e.Row.Cells(8).Text & "</span>"
 		e.Row.Cells(8).Text = str
 	End If
 End Sub

July 30, 2007 Posted by | ASP.NET, CSS, DataGridView, Google, MSN, Tips & Tricks, Yahoo | 1 Comment