A Demo of Customizing DataBound Data In Templates

This demo illustrates how to customize the output of databound data in a DataGrid template. The code would work equally as well in a template in a DataList or Repeater. This demo, specifically, illustrates how the databound output (here a couple of numeric values) can be made red if the data meets some certain conditions (has a value less than zero).

QuarterP & L Statement
Q1 2001
Revenue: 450391000
Profit: 102200111
Q2 2001
Revenue: 391000
Profit: -154950
Q3 2001
Revenue: -150938000
Profit: -902200

Source Code
<% @Import Namespace="System.Data" %>
<script language="vb" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
  End Sub
  Sub BindData()
	Dim pls as New DataTable()
	Dim dr as DataRow
	pls.Columns.Add(new DataColumn("Quarter", GetType(String)))
	pls.Columns.Add(new DataColumn("Revenue", GetType(Double)))
	pls.Columns.Add(new DataColumn("Profit", GetType(Double)))

    dr = pls.NewRow()
    dr(0) = "Q1 2001"
	dr(1) = 450391000
	dr(2) = 102200111
    dr = pls.NewRow()
    dr(0) = "Q2 2001"
	dr(1) = 391000
	dr(2) = -154950

    dr = pls.NewRow()
    dr(0) = "Q3 2001"
	dr(1) = -150938000
	dr(2) = -902200
	dgPLStmt.DataSource = pls
  End Sub

	Function MakeNegRed(input as String) as String
	  'See if the number is less than 0
	  If Int32.Parse(input) < 0 then
	    Return "<font color=""red"">" & input & "</font>"
	    Return input
	  End If
	End Function

<asp:DataGrid runat="server" id="dgPLStmt" AutoGenerateColumns="False">
    <asp:BoundColumn HeaderText="Quarter" DataField="Quarter" />
    <asp:TemplateColumn HeaderText="P & L Statement">
        <table border="0">
            <td align="right"><b>Revenue:</b></td>
            <td><%# MakeNegRed(DataBinder.Eval(Container.DataItem, "Revenue")) %></td>
            <td align="right"><b>Profit:</b></td>
            <td><%# MakeNegRed(DataBinder.Eval(Container.DataItem, "Profit")) %></td>

[Return to the article]