The formatting of a DataGrid cell’s string content can be configured using the .NET String.Format() method. Variations on the usual layout are given dependant upon whether the column is a bound column or a template column.
For string formatting the method is String.Format(formatString, string).
For example to show a today’s date in short data format, according to the local locale.
The label definition is taken from a section of a DotNetNuke module. The current date is assigned to the label using the String.Format() method, formatting it to show the date as described.
Protected WithEvents lblDate As System.Web.UI.WebControls.Label
lblDate.Text = String.Format(“d”,now())
For a bound column DataFormatString=”{d}” is added to the definition of the column.
For a template column the formatting into the reference to the data:
text='<%# DataBinder.Eval(Container, “DataItem.Total”, “{d}”) %>’
Examples of the use of the string formatting are given in the table below:
| Expression | Description |
|---|---|
| {0:C} | Currency item based on the locale, For example £19.99 |
| {0:D4} | The number is shown in decimal format, with padding defined by the number part. For example 199 shows as 0.0199. |
| {0:N2}% | A number with two decimal places, followed by a percentage sign: 19.99% |
| {0:0.0} | A number rounded to one decimal place: 19.9 |
| {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 |
To illustrate the above I have included below example template columns for a product name and price. 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.
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>' runat="server" id="lblName"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate HeaderTest="Price">
<asp:Label Text='<%# DataBinder.Eval(Container, "DataItem.price", "{0:N2}") %>' runat="server" id="lblPrice"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Giving a table similar to the one shown below
| name | Price |
|---|---|
| Apple | £1.99 |
| Plum | £2.99 |
| Banana | £6.58 |
| Kiwi | £8.76 |


