Thursday, June 4, 2009

DataFormatString to put leading zeros in ASP.NET GridView BoundField Column

If we want to display values like 0001, 0002 rather than 1,2 in the gridview columns, we need to make use of DataFormatString property of asp:BoundField in gridview.

So to put leading zeros or to zero pad the values displayed using bound field in gridview use this...

DataFormatString="{0:0000}"

To show the date in dd/MM/yyyy format, use this...

DataFormatString="{0:dd/MM/yyyy}"

This will be useful when we need to show only the date part and skip the time part.

:)

5 comments:

Rohan said...

There is a bug in older versions of the .NET 2.0 framework used for Visual Studio 2005. Even if you have a DataFormatString in your Gridview object, the column may still not format.

The workaround is to add the code

Code:
HtmlEncode ="false"

to that column

When HtmlEncode is on, the data is retrieved from the data store, Html Encoded, and then the format string is applied. By HtmlEncoding the value from the data store, the framework protects unsafe script from the data store from being displayed to the client.

http://www.group29.com/modules.php?name=News&file=article&sid=195

Simon said...

In normal C# code, if you want to pad zeros, you can do this

string str = "8";
string strPad = str.PadLeft(4,'0');

The result will be '0008'

This way you can add leading zeros. PadLeft is a general function, you can use any character in place of 0, if you want....

Unknown said...

CONVERT(char(10), Datetime, 102)
simply give date and

CONVERT(char(10), Datetime, 108)
simply give you time
then you format what ever you want.......Ericcisco.
by the way thanks for posting get good knowledge.
ericcisco

brainumbc said...

I don't know your exact requirements but if you add some whitespace on the end if should work and leave the leading zeros

If you're getting the field from sql try the following for the sqlfield

SELECT myfield + ' ' as myfield from mytable

brainumbc said...

Sorry there's suppose to be a nonbreaking space character in those quotes ' & nbsp ; '