In ASP.Net 2.0 GridView data control also provides the functionality to format the data item string using DataFormatString property of BoundColumn. DataFormatString property of GridView BoundColumn allows you to format the DataField value by concatenating a string with it or changing the string format using string formatting syntax e.g.: {0:N} for Number format, {0:C} for currency format, {0:X} for decimal to hexadecimal conversion etc. In this tutorial we have used the product table of Northwind SQL database to display the list of products and unit price of each product is formatted using {0:C} in the DataFormatString property of the BoundColumn. UnitsInStock column of the products table is formatted to number format using {0:N} in DataFormatString property of BoundColumn. You can learn the string format syntax from the tutorial about ASP.Net C# String Format Function
<style type="text/css">
font-family:arial;
}
.gridHeader th{
border-bottom:dashed 1px #c0c0c0;
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" GridLines="None" CellPadding="4" CellSpacing="0" HeaderStyle-HorizontalAlign="Left" Width="400px" RowStyle-CssClass="gridRow" CssClass="gridHeader">
<Columns>
<asp:BoundField DataField="unitprice" DataFormatString="${0:00.00}" HtmlEncode="false" HeaderText="Price (Formatted)" />
</asp:GridView>
From the above example code of GridView Control having DataFormatString property for BoundColumn you can see that HtmlEncode property is used with value false coz DataFormat String property supports the string format syntax only if HtmlEncode="false". There are two other types of string formatting used in the above example: ${0:00.00} it formats the DataField similar to currency format with $ sign and decimal number precision points upto 2 digits. You can also apply the same formatting for currency using {0:C2}, a digit after C in the given format syntax specifies the number of decimal point precisions.
Output:
You can download the C# code to bind GridView Control with Northwind SQL Database at:
ASP.Net GridView Highlight Row onmouseover
Be the first to rate this post
Tags: asp.net 2.0, c#, asp.net gridview, asp.net gridview dataformatstring, asp.net string format function, c# string format, c# convert number to currency, asp.net gridview date, asp.net gridview dataformatstring date
10/11/2008 3:44:00 AM