How to use DetailsView DataBound Event to customize the format of data

This article demonstrates how to use DetailsView Control's DataBound Event Handler to customize formatting of data. Sections of the DetailsView control can be customized using the following properties of the DetailsView control:
  • HeaderStyle
  • RowStyle
  • AlternatingRowStyle

These properties are also known as style-related properties.

For example, in a Closing stock report, we may want to format and display closing stock quantity of those items which have quantities below a certain level. We can show these quantities either in bold or in italic. In this example, we will accomplish the task by using the DataBound event of the detailsView control. The databound event is raised immediately after the DetailsView control is bound to its data source.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailsViewDataBound.aspx.cs" 
Inherits="DetailsViewDataBound" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<head runat="server">
    <style type="text/css">

    font-weight: bold;
    font-style: italic;

    <title>Untitled Page</title>
    <form id="form1" runat="server">
   <asp:DetailsView ID="ItemsDetailsView" runat="server"  
   AllowPaging="true" DataKeyNames="ItemID" 
   DataSourceID="MyDataSource"  AutoGenerateInsertButton="true" 
<asp:label id="Message"    forecolor="Red"    runat="server"/>
<asp:SqlDataSource ID="MyDataSource"  
SelectCommand="SELECT ItemID,ItemName,ItemType,ClStk FROM ItemTable" 
runat="server"        />

output of DetailsView DataBound Event

Writing an event handler for a DataBound event

In order to display the closing stock quantity of items whose closing stock is below zero, in a bold and italic font, we need to create an event handler for the DataBound event. Using the DataBound event handler, we retrieve all the data that has been bound to the DetailsView control. The below is the code for the DataBound event handler.

protected void ItemsDetailsView_DataBound(object sender, EventArgs e)
        if (Convert.ToInt16(ItemsDetailsView.Rows[3].Cells[1].Text) <= 0)
            ItemsDetailsView.Rows[3].Cells[1].CssClass = "changefont";

The next step is to get the value of a ClStk field in a DataBound event handler. In the DataBound event handler, we can retrieve the closing stock quantity programatically using the below statement.


The Clstk (closing stock quantity) is in the fourth row of the DetailsView control and index 3 indicates the fourth row.