Friday, April 10, 2009

How to format GridView Rows/Columns in Design/Run time

Here i will discuss how you can format data in GridView rows. Most of the time we require to render our GridView control by custom formatting since data source format does not contain our exact required formats. Like, you want to display numeric values in two decimal format or want to display short date instead of considering time portion from databse. In this post i will try to resolve below issues:

***
How to format date/numeric data in GridView in design time
*** How to format data in GridView in run time/code behind
*** How to format Template Column
*** How to use DataFormatString property to format data
*** What is HtmlEncode?

List of Date Formats:

Format characterDescriptionPatternExample
dShort dateMM/dd/yyyy12/1/2009
DLong datedddd, dd MMMM yyyySunday, April 12, 2009
tShort timeHH:mm5:12 PM
TLong timeHH:mm:ss5:12:00 PM
fFull date/time(short time)dddd, dd MMMM yyyy HH:mmSunday, April 12, 2009 5:12 PM
FFull date/time(long time)dddd, dd MMMM yyyy HH:mm:ssSunday, April 12, 2009 5:12:00 PM
gGeneral date/time(short time)MM/dd/yyyy HH:mm4/12/2009 5:12 PM
GGeneral date/time(long time)MM/dd/yyyy HH:mm:ss4/12/2009 5:12:00 PM
m or MMonth dayMMMM ddApril 12
r or RGMTddd, dd MMM yyyy HH':'mm':'ss 'GMT'Sun, 12 Apr 2009 7:12:00 GMT
sSortable date/timeyyyy'-'MM'-'dd'T'HH':'mm':'ss2009-04-12T14:12:00
uUniversalSortableDateTimePattern using universal timeyyyy'-'MM'-'dd HH':'mm':'ss'Z'2009-04-12 14:12:00z
UFull date and time (long date and long time) using universal timedddd, dd MMMM yyyy HH:mm:ssSunday, April 12, 2009 10:12:00 PM
y or YYear monthMMMM yyyyApril, 2009


Format date in bound column:

Consider we have a GridView that displays Supplier information with Code, Name, Address, Contact no and Supply date where the Supply date is stored with time in database. To do that for bound column apply the below technique:

<asp:BoundField DataField="LastDelivery" HeaderText="Recent Delivery" DataFormatString = "{0:y}" HtmlEncode="false"></asp:BoundField>


OR

<asp:BoundField DataField="LastDelivery" HeaderText="Recent Delivery" DataFormatString = "{0:MMMM yyyy}" HtmlEncode="false"></asp:BoundField>


If you want to format date using SQL query then Click Here.

i.e. You can use both format or pattern column to format date column like below:



Formatting columnar data in a GridView code-behind:

protected void gvEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{if (e.Row.RowType == DataControlRowType.DataRow)
{e.Row.Cells[4].Text = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["LastDelivery"]).ToString("y");
}
}


Format Template Column:
Add a template column with textbox/label etc.. then format it in the below way:

<asp:TemplateField HeaderText="Recent Delivery">
<ItemTemplate><asp:Label ID="lbl" runat="server" Text='<%# Eval("LastDelivery", "{0:y}") %>'></asp:Label
>
</ItemTemplate></asp:TemplateField>



List of Numeric Formats:

FormatDescriptionExample
CCurrency format$10.00
DDecimal format10
EScientific format1.000000E+001
FFixed format10.00
GGeneral format10
NNumber format10.00
XHexadecimal formatA

Note: Format characters are not case-sensitive, except for "X"

The value after the format character specifies the number of significant digits or decimal places to display. For example, the formatting string "{0:F2}" displays a fixed-point number with two decimal places.

Format numeric data in bound column:

<asp:BoundField DataField="Price" HeaderText="Price" DataFormatString="{0:C2}" HtmlEncode="false">


Format numeric data in Template Column:

<asp:TemplateField HeaderText="Recent Delivery">
<ItemTemplate
>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("Price", "{0:C2}") %>'></asp:Label
>
</ItemTemplate
>
</
asp:TemplateField>


Formatting columnar data in a GridView code-behind:

protected void gvEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
((Label)e.Row.FindControl("lbl")).Text = Convert.ToDecimal(((DataRowView)e.Row.DataItem)["ID"]).ToString("C5");
}



You may need to add few prefix like AU/US then use :
DataFormatString="AU {0:C5}" HtmlEncode="false"
OR
DataFormatString="US {0:C5}" HtmlEncode="false"



NOTE: Most of the beginner forget to add HtmlEncode="false"

What is HtmlEncode?
Microsoft introduced this new property to prevent cross site scripting (CSS) attacks. This way if there is any malicious text in the fields, it will get encoded and will not executeon client's browser. If this property is set to true, the formatting implementation in the control first encoded the text using HttpUtility.HtmlEncode. And after that it calls String.Format method on the encoded text value.Where as when HtmlCode is set to false, the formatting is done on the data value itself. So the way to fix your problem with formatting would be to set HtmlEncode property to false.

To Read More:
http://msdn.microsoft.com/en-us/library/aa479342.aspx
http://www.netomatix.com/development/gridviewcustomdataformatting.aspx

6 comments:

Anonymous said...

Coool, thanks, i have added this in my bookmark,
Cheers Bangladesh
i am from uttara

Anonymous said...

well written article , keep up the good work

Cheers
India

Anonymous said...

How did you replace the number in the Contact column with those characters? Thanks

Anonymous said...

good reference!

Anonymous said...

thanks

Anonymous said...

thanks from padania

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash