Oleg Ogurok wrote:
Hi all,
I have a DatePicker ASP.NET control that allows users to enter date (e.g. a
calendar control). The control has the following property
public DateTime Value { get; set; }
I've placed the control into a datagrid now I'm trying to bind values from
database to the datagrid.
<ctl:DatePicker id="Datepicker1" runat="server" Value='<%#
DataBinder.Eval(Container, "DataItem.MyDateField") %>'>
</ctl:DatePicker>
The problem arises where the value in DB is NULL. I get
"System.InvalidCastException: Specified cast is not valid"
I've looked into the .cs file generated from .aspx under "Temporary ASP.NET
Files" and found this code:
#line 15 "N:\WebStaging\DatePickerTest.aspx"
target.Value = ((System.DateTime)(DataBinder.Eval(Container,
"DataItem.MyDateField")));
At runtime the value from DataBinder.Eval() evaluates into DBNull.Value, and
then it's casted into System.DateTime causing the error.
I am wondering if there was any way to control the generated C# code.
Basically, I want DBNull values to be translated into DateTime.MinValue for
instance.
Thanks,
Oleg.
Basically you just need to wrap up what you have defined in a 'helper
method' call. Declare a protected method in your code-behind, pass the
existing binding expression as its argument. Something like
Value='<%# myHelper(DataBinder.Eval(Container, "DataItem.MyDateField"))%>'
where myHelper is the method I assume in the code-behind. Then you can
massage the data if needed in the function, as it's called for each item....
An in-depth example is here:
http://www.c-sharpcorner.com/Code/20...tDataListt.asp
--
Craig Deelsnyder
Microsoft MVP - ASP/ASP.NET