Robert McLaws: FunWithCoding.NET

Public Shared Function BrainDump(ByVal dotNet As String) As [Value]

News

<script type="text/javascript"><!-- google_ad_client = "pub-4330602465258980"; google_hints = "ASP.NET, VB.NET, C#, C#.NET, WindowsForms, .NET Framework, VS2005, Visual Studio, XAML, WinFX, Windows Workflow, WPF, WCF, Atlas, NetFX3, Visual Studio Orcas"; google_ad_width = 120; google_ad_height = 240; google_ad_format = "120x240_as"; google_ad_type = "text_image"; google_ad_channel ="4997399242"; google_color_border = "B6C9E7"; google_color_bg = "EFEFEF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "002C99"; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<!--
-->

You should feel free to challenge me, disagree with me, or tell me I'm completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever. That said, I will most likely only delete abusive, profane, rude, or annonymous comments, so keep it polite, please.

Blogroll

Cool .NET Articles

My .NET Tools

My Builder.com Articles

My MSKB Articles

Complex DataBinding with Date Formats in .NET 1.1

Did you know that you can do some pretty complex things with .NET's late binding in ASP.NET 1.X? I had a problem where I needed to be able to kick out dates in a specific format. I didn't want to use a helper method, which involves compiled code, so I found a solution.

1<%# CType(DataBinder.Eval(Container.DataItem, "DateAdded"), DateTime).ToString("dd MMM yyyy") %>

Your datatype on the DataItem can be a string or a DateTime object. Either way, you must do the conversion first, otherwise there would be an implicit conversion, which is not allowed in late-binding code. The bold part is the name of the date property on the object you are binding against.

As with any late-binding, you'll have a slight performance delay on the first hit, but that's just cause the page is recompiling. It'll be fine after that.

Comments

Matt Berther said:

How about

DataBinder.Eval(Container.DataItem, "DateAdded", "dd MMM yyyy")

Same thing... without the cast.
# September 30, 2004 1:48 AM

Robert McLaws said:

Nope, doesn't work. I get "dd MMM yyyy" as my value. That's why I had to cast...
# September 30, 2004 2:02 AM

LeeB said:

Or you could use:

CType(Container.DataItem.DateAdded, DateTime).ToString("dd MMM yyyy")

I find it a bit more compact and easier to read.
# September 30, 2004 2:53 AM

Johnny Hall said:

Try

DataBinder.Eval(Container.DataItem, "DateAdded", "{0:dd MMM yyyy}")

or (depending on the type of Container.DataItem) (c# code)

((DataRowView) Container.DataItem)["DateAdded"].ToString("dd MMM yyyy")

to avoid the use of reflection in the .Eval.
# September 30, 2004 9:02 AM