Mar 15, 2011

Change the color of data in GridView based on its value

In this article, I will demonstrate a simple way to change the color of the data in a GridView based on its value.
Let's set the stage. The GridView in this example will display three different products, each having the following attributes:
  • Product Name - the name of the product
  • Price - a number representing the product's price
  • In Stock - a Boolean value representing if a product is in stock
The value in the "In Stock" column will be either a green true value if the product is in stock or a red false value if the product is out of stock. The following image illustrates what the result will look like:
GridView
First, create a new ASPX web page and add the GridView server control to it as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
                <asp:BoundField DataField="Price" HeaderText="Price" />
                <asp:BoundField DataField="InStock" HeaderText="In Stock" />
            </Columns>
        </asp:GridView>

    </div>
    </form>
</body>
</html>
No magic here. We declared a GridView server control and set the AutoGenerateColumns to false so
that we may add the columns manually. In addition, we added a BoundField control for each of the
columns.Switch to the code behind page and add the following code to the Page_Load event:


.. 

protected void Page_Load(object sender, EventArgs e)
{    
    // Create a DataTable object to hold the products.    
    System.Data.DataTable products = new System.Data.DataTable();     
    
    // Create the columns to represent the products attributes.    
    products.Columns.Add("ProductName", Type.GetType("System.String"));    
    products.Columns.Add("Price", Type.GetType("System.Double"));    
    products.Columns.Add("InStock", Type.GetType("System.Boolean"));     
    
    // Add the first record.    
    products.Rows.Add();    
    products.Rows[0]["ProductName"] = "Pen";        
    products.Rows[0]["Price"] = ".89";    
    products.Rows[0]["InStock"] = "True";     
    
    // Add the second record.    
    products.Rows.Add();    
    products.Rows[1]["ProductName"] = "Stapler";    
    products.Rows[1]["Price"] = "5.99";    
    products.Rows[1]["InStock"] = "False";     
    
    // Add the third record.    
    products.Rows.Add();    
    products.Rows[2]["ProductName"] = "Glue";    
    products.Rows[2]["Price"] = "2.29";    
    products.Rows[2]["InStock"] = "True";     
    
    // Set the products DataTable as the DataSource for the GridView    
    // and Bind it.    
    GridView1.DataSource = products;    
    GridView1.DataBind();
} 

...
 
in a real life scenario, the GridView will most likely get its data from a Database,
       XML file or some other data source, but in this example we will create a 
simple  DataTable object and populate it with some data to represent the products.
        
The first line of code in the Page_Load event creates a DataTable object called products. The next three lines illustrate how to declare the columns that will represent the product attributes. The next few lines illustrate how to add records to the products DataTable object. Finally, the last two lines assign the products DataTable to the GridView and binds it.
If you were to run the web page as is, the results would look similar to the following image:
GridView
Now the fun begins. To help us distinguish products that are in stock from out of stock, we are going to change the color of all true values to green and all false values to red. To accomplish this trick, add a new method named InStockColor in the code behind page as follows:

... 

public System.Drawing.Color InStockColor(string inStock)
{    
    // Test inStock
    // if True return Green, else return Red.    
    if (bool.Parse(inStock))        
        return System.Drawing.Color.Green;    
    else        
        return System.Drawing.Color.Red;
} 

...
The InStockColor method takes a string argument representing the value of the In Stock column. It then tests the value to determine if it is either true or false. Based on the value it returns a Green color for true and a Red color for false.
Switch to the ASPX web page and modify the GridView as follows to call the InStockColor method:

 ...
        
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:TemplateField>
            <HeaderTemplate>In Stock</HeaderTemplate>
            <ItemTemplate> 
                <asp:Label ID="InStockLabel" 
                    runat="server" 
                    Text='<%# Eval("InStock") %>' 
                    ForeColor='<%# InStockColor(Eval("InStock").ToString()) %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

...
 
The only update that was made to the GridView was to change the InStock column from BoundField to TemplateField. The TemplateField provides us with greater control on how to display the column. We used a Label server control and bound its Text and ForeColor properties using the DataBinder Eval() method. Eval() is used to evaluate data-binding expressions during run time. To set the correct color, we set the label’s ForeColor property to the InStockColor method and passed in the value of InStock. The InStockColor method will determine the value and return the appropriate Color to the property.
If you were to rerun the web page again, the results would look similar to the following image.
GridView, color
That was pretty painless. In this article, I demonstrated a simple approach to add some colors to the values in GridView during run time.
Hope this article was useful to you.

--------vamsi--------------------
 



 


 

No comments:

Post a Comment