Conditionally Change a DataGrid Column Value...
By: John Kilgo Date: February 27, 2003 Download the code.

There are times when you will need to highlight or otherwise modify the contents of a particular DataGrid row-column value based upon the value in the column. In this example we will select the CompanyName, ContactName, and ContactTitle columns from the Customers table in the Northwind database. Whenever the value of ContactTitle equals "Owner" we will change the font color to red.

We can do this by using an ItemTemplate where we have complete control over the presentation of the data. We use BoundColumns for the first two columns and an ItemTemplate for the ContactTitle column. Within the ItemTemplate we call a function named "ChangeColors" and pass it the value of the column. This is what the line <%# ChangeColor(Container.DataItem("ContactTitle")) %> does. We are getting the value of ContactTitle and passing it to the ChangeColor function which appears in our code-behind page.

<%@ Page Language="vb" Src="CondDataGrid.aspx.vb" Codebehind="CondDataGrid.aspx.vb" Inherits="CondDataGrid" AutoEventWireup="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>CondDataGrid</title>
<meta content="Microsoft Visual Studio.NET 7.0" name=GENERATOR>
<meta content="Visual Basic 7.0" name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
</head>
<body MS_POSITIONING="GridLayout">
<form id=Form1 method=post runat="server">
<asp:DataGrid ID="dataGrid"
              AutoGenerateColumns = "False"
              Runat="server">
  <Columns>
    <asp:BoundColumn HeaderText="Company Name" DataField="CompanyName" />
    <asp:BoundColumn HeaderText="Contact Name" DataField="ContactName" />

    <asp:TemplateColumn HeaderText="Contact Title">
      <ItemTemplate>
        <%# ChangeColor(Container.DataItem("ContactTitle")) %>
      </ItemTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:DataGrid>
</form>
</body>
</html>

Most of the code-behind file is the usual data access code to get our resultset. At the bottom of the file, color-coded in blue, is the ChangeColor function. As you can see, all it is doing is checking for "Owner" in the value passed in. If the value is "Owner" then we put font tags around the value and send it back. Otherwise, if it was not "owner", we just send the value back to the caller to be rendered as is.

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Class CondDataGrid
    Inherits System.Web.UI.Page

Protected WithEvents dataGrid As System.Web.UI.WebControls.DataGrid

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim sqlConn As SqlConnection
    Dim sqlCmd As SqlCommand

    Try
      sqlConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
      sqlCmd = New SqlCommand("SELECT TOP 10 * FROM Customers", sqlConn)
      sqlConn.Open()
      dataGrid.DataSource = sqlCmd.ExecuteReader()
      dataGrid.DataBind()
    Catch ex As Exception
      Response.Write(ex.ToString() & "<br>")
    Finally
      sqlConn.Close()
      sqlConn.Dispose()
    End Try
  End Sub

  Function ChangeColor(value)
    If value = "Owner" Then
      ChangeColor="<font color='red'>" & value & "</font>"
    Else
      ChangeColor = value
    End If
  End Function


End Class

I hope you have seen how easy it is to modify the appearance of a DataGrid colum based upon its value. You can, of course, base your modifications on the value of any column you want.

You may run the example program here.
You may download the code here.