Format decimal in ASP.Net

I am doing this dorknozzle exercise from the book, and my prices are not formatting correctly:

i’m not sure how or where to insert the code to “round” the prices to two decimals.

here is the code:

<%@ Import Namespace=“System.Data.SqlClient” %>
<%@ Import Namespace=“System.Data” %>

<title>Employee Store</title>
<link href=“styles.css” rel=“stylesheet” />
<script runat=“server” language=“C#”>

SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings[“DSN”]);
SqlDataAdapter objDA;
DataSet objDS = new DataSet();
DataRow objDR;
DataTable objCartDT;

void Page_Load() {
if (!IsPostBack) {
objDA = new SqlDataAdapter(“SELECT * FROM EmployeeStore”, objConn);
objDA.Fill(objDS, “Store”);
dlItems.DataSource = objDS;
pnlShowCart.Visible = false;
objCartDT = (DataTable)Session[“Cart”];
if (objCartDT == null) {
objCartDT = new DataTable(“Cart”);
objCartDT.Columns.Add(“CartID”, typeof(Int32));
objCartDT.Columns[“CartID”].AutoIncrement = true;
objCartDT.Columns[“CartID”].AutoIncrementSeed = 1;
objCartDT.Columns.Add(“ItemID”, typeof(Int32));
objCartDT.Columns.Add(“Quantity”, typeof(Decimal));
objCartDT.Columns.Add(“Item”, typeof(string));
objCartDT.Columns.Add(“Cost”, typeof(Decimal));
Session[“Cart”] = objCartDT;

void AddToCart(Object s, DataListCommandEventArgs e) {
pnlShowItems.Visible = false;
pnlShowCart.Visible = true;

int ItemID = Convert.ToInt32(dlItems.DataKeys[e.Item.ItemIndex]);
DataSet objItemInfo = FindItem(ItemID);

bool blnMatch = false;
foreach (DataRow objDR in objCartDT.Rows) {
	if (Convert.ToInt32(objDR["ItemID"]) == ItemID) {
		int Quantity = Convert.ToInt32(objDR["Quantity"]);
		Quantity += 1;
		objDR["Quantity"] = Quantity;
		blnMatch = true;
if (!blnMatch) {
	objDR = objCartDT.NewRow();
	objDR["ItemID"] = ItemID;
	objDR["Item"] = objItemInfo.Tables["ItemInfo"].Rows[0]["ItemName"];
	objDR["Quantity"] = 1;
	objDR["Cost"] = objItemInfo.Tables["ItemInfo"].Rows[0]["Cost"];

dgCart.DataSource = objCartDT;
lblTotal.Text = "$" + GetItemTotal();


DataSet FindItem(int ItemID) {
DataSet objItemInfo = new DataSet();

objDA = new SqlDataAdapter("SELECT * FROM EmployeeStore WHERE ItemID=" + ItemID, objConn);
objDA.Fill(objItemInfo, "ItemInfo");

return objItemInfo;


Decimal GetItemTotal() {
decimal decRunningTotal = 0;

foreach (DataRow objDR in objCartDT.Rows) {
	decRunningTotal +=
		Decimal.Round(Convert.ToDecimal(objDR["Cost"]) *
			Convert.ToInt32(objDR["Quantity"]), 2);
return decRunningTotal;


void dgCart_Edit(Object s, DataGridCommandEventArgs e) {
dgCart.EditItemIndex = e.Item.ItemIndex;

dgCart.DataSource = objCartDT;


void dgCart_Cancel(Object s, DataGridCommandEventArgs e) {
dgCart.EditItemIndex = -1;

dgCart.DataSource = objCartDT;


void dgCart_Update(Object s, DataGridCommandEventArgs e) {
TextBox txtQuantity;
int intCartID;

intCartID = Convert.ToInt32(dgCart.DataKeys[e.Item.ItemIndex]);
txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");

foreach (DataRow objDR in objCartDT.Rows) {
	if (intCartID == (int)objDR["CartID"]) {
		objDR["Quantity"] = Convert.ToInt32(txtQuantity.Text);
lblTotal.Text = "$" + GetItemTotal();
dgCart.EditItemIndex = -1;

dgCart.DataSource = objCartDT;


void dgCart_Delete(Object s, DataGridCommandEventArgs e) {

dgCart.DataSource = objCartDT;

lblTotal.Text = "$" + GetItemTotal();


void ContinueShopping(Object s, EventArgs e) {
pnlShowCart.Visible = false;
pnlShowItems.Visible = true;


void CheckOut(Object s, EventArgs e) {
String cartBusiness = “”;
String cartProduct;
int cartQuantity;
decimal cartCost;
int itemNumber = 1;

cartBusiness = Server.UrlEncode(cartBusiness);

String strPayPal = "" +
	"?cmd=_cart&upload=1&business=" + cartBusiness;
foreach (DataRow objDR in objCartDT.Rows) {
	cartProduct = Server.UrlEncode((string)objDR["Item"]);
	cartQuantity = (int)objDR["Quantity"];
	cartCost = (Decimal)objDR["Cost"];
	strPayPal += "&item_name_" + itemNumber + "=" + cartProduct;
	strPayPal += "&item_number_" + itemNumber + "=" +
	strPayPal += "&amount_" + itemNumber + "=" +
		Decimal.Round(cartQuantity * cartCost, 2);

<form runat=“server”>

<table width=“100%” border=“0” cellspacing=“0” cellpadding=“0” background=“Images/header_bg.gif”>
<td><img src=“Images/header_top.gif” width=“450” height=“142” alt=“ the official dorknozzle company intranet” /></td>

<table width=“100%” border=“0” cellspacing=“0” cellpadding=“0”>
<td width=“157”><img src=“Images/header_bottom.gif” width=“157” height=“37” alt=“” /></td>

<table width=“100%” border=“0” cellspacing=“0” cellpadding=“10”>
<td valign=“top” width=“160”>
<!-- HyperLink Controls for navigation –>
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“index.aspx” runat=“server” Text=“Home” /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“helpdesk.aspx” runat=“server” Text=“HelpDesk” /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“employeestore.aspx” runat=“server” Text=“Employee Store” /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“newsletterarchive.aspx” runat=“server” Text=“Newsletter Archive” /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“employeedirectory.aspx” runat=“server” Text=“Employee Directory” /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“addressbook.aspx” runat=“server” Text=“Address Book” /><br /><br />
<img src=“Images/book_closed.gif” width=“16” height=“16” alt=“+” /><asp:HyperLink NavigateUrl=“admintools.aspx” runat=“server” Text=“Admin Tools” />
<!-- End HyperLink Controls –>
<td valign=“top”>
<asp:panel ID=“pnlShowItems” runat=“server”>
<h1>Employee Store</h1>
<asp:datalist ID=“dlItems” runat=“server” DataKeyField=“ItemID” OnEditCommand=“AddToCart”>
<table width=“400” border=“0” cellspacing=“0” cellpadding=“0”>
<td width=“200” valign=“top” align=“center”>
<img src=“<%# DataBinder.Eval(Container.DataItem, “ImageURL”) %>” />
<td width=“200”>
<strong><%# DataBinder.Eval(Container.DataItem,“ItemName”) %></strong>
<br />
Cost: $<%# DataBinder.Eval(Container.DataItem,“Cost”) %><br /><br />
<asp:button ID=“btnAddToCart” runat=“server” Text=“Add To Cart” CommandName=“Edit” />
<td colspan=“2” width=“400”><hr noshade height=“1” />
<asp:panel ID=“pnlShowCart” runat=“server”>
<h1>View Cart</h1>
<asp:datagrid ID=“dgCart” runat=“server” AutoGenerateColumns=“false” GridLines=“None”
CellPadding=“3” Width=“100%” DataKeyField=“ItemID” OnEditCommand=“dgCart_Edit”
OnCancelCommand=“dgCart_Cancel” OnUpdateCommand=“dgCart_Update” OnDeleteCommand=“dgCart_Delete”>
<headerstyle Font-Name=“arial” Font-Size=“10” />
<asp:editcommandcolumn EditText=“Edit” CancelText=“Cancel” UpdateText=“Update” />
<asp:buttoncolumn ButtonType=“LinkButton” Text=“Remove” CommandName=“Delete” />
<asp:boundcolumn DataField=“Item” HeaderText=“Product Name” ReadOnly=“true” />
<asp:templatecolumn HeaderText=“Quantity”>
<%# DataBinder.Eval(Container.DataItem,“Quantity”) %>
<asp:textbox ID=“txtQuantity”
Text=‘<%# DataBinder.Eval(Container.DataItem,
“Quantity”) %>’
runat=“server” Width=“50” />
<asp:boundcolumn DataField=“Cost” HeaderText=“Cost” ReadOnly=“true” />
<p align=“right”><strong>Total: <asp:label ID=“lblTotal” runat=“server” /></strong></p>
<p align=“right”><asp:linkbutton ID=“lbContinue” Text=“Continue Shopping” runat=“server” OnClick=“ContinueShopping” /> |
<asp:linkbutton ID=“lbCheckout” Text=“Checkout” runat=“server” OnClick=“CheckOut” /></p>



Any Help would be greatly appreciated.


Try replacing

<%# DataBinder.Eval(Container.DataItem,"Cost") %>


<%# String.Format("{0:c}", DataBinder.Eval(Container.DataItem,"Cost")) %>

Or better yet, the overload of DataBinder.Eval:

<&#37;# DataBinder.Eval(Container.DataItem, "Cost", "{0:c}") %>

Does the same thing as tony’s example, but it is more cannonical. And it should handle potential nulls better.

Thanks guys…that worked perfectly. Could you please explain what this is doing? I’m pretty new to C#.

Thanks again!:slight_smile:

.NET has alot of builtin string formatting functionality for various data types, but especially for DateTime and the whole gamut of numeric types. These numbers are formatted using custom format strings–like the ‘c’ part above (which means format it like currency). To reference places, you use a 0-based index (the 0 above). Finally, MS provides a way to feed this string to any databound expression (see above).

Anyhow, rather than stumble through it myself, see the formatting overview in the .NET manual.