Change Color of a Column Based on Column Values


Introduction:

In this article we'll see how to change the color of column based on the column value.

We'll consider the Northwind Database and Products Table. We have a field UnitsInStock in the Products Table. If the UnitsInStock is less than 15 we'll display the value in red color else green.

Snippet:

Create a webform with a DataGrid control. 
<asp:DataGrid id="DataGrid1" AutoGenerateColumns =false style="Z-INDEX: 101; LEFT: 18px; POSITION: absolute; TOP: 18px" runat="server">
<
Columns> <asp:TemplateColumn > <HeaderTemplate >
<table border=0 width="100%">
<tr>
<td>ProductID</td>
<
td>ProductName</td>
<
td>UnitPrice</td>
</
tr>
</
HeaderTemplate>
<ItemTemplate >
<tr>
<td><%#DataBinder.Eval(Container.DataItem , "ProductID")%></td>
<
td><%#DataBinder.Eval(Container.DataItem , "ProductName")%></td>
<
td><font Color ="<%#PickColor(DataBinder.Eval(Container.DataItem , "UnitsInStock"))%>"> <%#DataBinder.Eval(Container.DataItem , "UnitsInStock")%>
</font></td>
</
tr>
</
ItemTemplate>
<FooterTemplate >
</table>
</
FooterTemplate>
</
asp:TemplateColumn>
</
Columns>
</asp:DataGrid>

In the code behind write the code which picks the color based on the value of the UnitsInStock.

Here goes the code:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim myconnection As SqlConnection = New SqlConnection("server=localhost;uid=sa;password=; database=northwind")
Dim myda As SqlDataAdapter = New SqlDataAdapter("Select * from Products", myconnection)
Dim ds As DataSet = New DataSet
myda.Fill(ds, "AllTables")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
'Function to pick up the color based on th UnitsInStock Value
Function PickColor(ByVal fldval As Double) As String
Dim color As String
If fldval < 15 Then
color = "Red"
Return color
Else
color = "green"
Return "green"
End If
End
Function

Up Next
    Ebook Download
    View all
    Learn
    View all