Formatting Datagrid Data Text Two Ways

Data grid output can be formatted differently for the public/normal view and the edit view.

In this example both methods are used.

Using inline table row editing with a DataGrid I wished to change the formatting according to its state.

To illustrate this I have included below an example template column.

<HEADERSTYLE HorizontalAlign="Center"></HEADERSTYLE>
<ITEMTEMPLATE>
<asp:Label Text=‘<%# DataBinder.Eval(Container, "DataItem.price", "{0:c}") %>’ runat="server">
</asp:Label>
</ITEMTEMPLATE>
<EDITITEMTEMPLATE>
<asp:TextBox id="price" Text=‘<%# DataBinder.Eval(Container, "DataItem.price", "{0:N2}") %>’ runat="server" Columns="6">
</asp:TextBox>
</EDITITEMTEMPLATE>

We are able to format the content of the DataGrid cell by one of two methods, dependent upon whether the column is a bound column or whether it is a template column.

As can be seen two different formatting styles are used.

When the DataGrid is normally viewed the currency format is displayed and when the row is being edited we switch to a 2 decimal place view. To provide the number in a suitable format, without the presentation of the currency symbol. After all a currency symbol within the textbox will give us an extra unnecessary item to handle.

Bound column

For the bound column I’ve added DataFormatString=”{0:N2}%” to the definition of the column.

Looking at the table below, we can see that in our example, we shall format the column to have two digits after the decimal point, followed by a percentage sign.

Template column

For the template column I’ve added the formatting into the reference to the data:

text=‘<%# DataBinder.Eval(Container, “DataItem.Total”, “{0:N2}%”) %>’

Formatting

The table below summarises the formatting expressions with their results.

ExpressionDescription
{0:C}Currency item based on the locale, For example £29.99
{0:D4}A number of the set number plus 1. For example 00124
{0:N2}%A number with two decimal places, followed by a percentage sign
{0:0.0}A number rounded to one decimal place.
{0:D}The date represented as a long string. For example Monday, 20 July 2004
{0:dd-MM-yy}The number as defined by the day, month and year code. for example 20-07-04