Date format in repeater control

Z

zdrakec

Hello all:

I'm having no problem with formatting a date, when I have one, but when
the Container.DataItem is DBNull, then my date formatting blows up
(Cast from DBNull to Date not valid). I've tried numerous ways of
testing for DBNull before doing the format, but have had no luck...

Any ideas?

Thanks much,

zdrakec
 
Z

zdrakec

Never mind, got it:

DataBinder.Eval(Container.DataItem,"DateField","{0:MM/dd/yyyy}")

Simple really...

Thanks anyway!!
 
T

Teemu Keiski

Hi,

if you don't need to cast to a date first, you could simply have a
databinding expression in the aspx. For example:

<asp:TemplateColumn>
<ItemTemplate>
<%#
DataBinder.Eval(Container.DataItem,"database_field_name","{0:dd.MM.yyyy}")%>
</ItemTemplate>
</asp:TemplateColumn>

where "{0:dd.MM.yyyy}" indicates the formatting. Now, databinding
expressions should not blow up with null values (DBNull), they just produce
empty string.

However, if you need to cast to a date in code, you can nothing but check
for the DbNull value from the field with IsDbNull function (VB) or
Convert.IsDbNull (Framework/C#) which return boolean value indicating if the
value is DbNull. When there is a DbNull (per previous methods) you just
outout empty string (or other predefined string such as -No date-), you
cannot cast it to a Date. So it means that this check should happen before
trying casting.
 
Z

zdrakec

Right, that is what I was doing, only I wasn't using the Eval... in
other words, I was trying to do:

IIF(IsDBNull(datavalue),"",Format(datavalue,"MM/dd/yyyy"))

which was failing because the IIF does not behave like
If..AndAlso...End If nor like If...OrElse...End If, and I was treating
it as though it did; so the "false" condition of the IIF was getting
examined, and blowing up for DBNull values.

I changed it to

IIF(IsDBNull(Container.DataItem("DateField")),"",DataBinder.Eval(Container.DataItem,"DateField","{0:MM/dd/yyyy}"))

which works just fine since the DBNull evaluates to an empty string, as
you said.

Thanks!
zdrakec
 
T

Teemu Keiski

It is better to use If Else explicitly with these, or self-made helper
library functions. As you say, IIF always executes both functions despite
the outcome of the first expression which defines what is returned.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top