Note that there are some explanatory texts on larger screens.

plurals
  1. POSpecified Cast is not valid when DataBind to Nullable DateTimeOffset and field is NULL
    text
    copied!<p>I've created a simple CompositeControl and exposed a Nullable DateTimeOffset property. I'm binding the control to a SQL Server DateTimeOffset field using</p> <pre><code>DateTimeOffset='&lt;%# Bind("myDateTimeOffsetField") %&gt;' </code></pre> <p>This works great when the DateTimeOffset field has a value. But when the field is NULL I get a "Specified Cast is not valid" error.</p> <p>How do I stop this error and set my property to Nothing when the field is NULL?</p> <p>I thought this would be the default behaviour!</p> <p>Property definition is:</p> <pre><code>Public Property DateTimeOffset As DateTimeOffset? </code></pre> <p><strong>Later comment:</strong></p> <p>I've found that this works if I change from using Bind to:</p> <pre><code>DateTimeOffset='&lt;%# iif(IsDbNull(Eval("myDateTimeOffsetField")), Nothing, Eval("myDateTimeOffsetField")) %&gt;' </code></pre> <p>But then I don't get "myDateTimeOffsetField" passed as an argument in the FormView.ItemUpdating event (yes, this is in a FormView control) since ASP.NET assumes I'm not binding back to the Database.</p> <p><strong>Actual Code (Added by Request)</strong></p> <p>This is the Property in my Composite Control that I'm trying to bind to:</p> <pre><code>Public Property DateTimeOffset As DateTimeOffset? Get Return CType(ViewState("DTO"), DateTimeOffset?) End Get Set(value As DateTimeOffset?) ViewState("DTO") = value End Set End Property </code></pre> <p>Heres the markup for the Binding. The Control is in the EditItemTemplate of a FormView which is bound to a SQL DataSource returning a field called [dtoMldRejOn] with an optional DateTimeOffset value.</p> <pre><code>&lt;APS:DateTimeOffsetControl runat="server" id="dtocMldRejOn" TextBoxCssClass="inputdatetime" ValidationGroup="vw1" FieldName="&lt;%$ Resources: Resource, rxgFrom %&gt;" DateTimeOffset='&lt;%# Bind("dtoMldRejOn") %&gt;' WindowsTimeZoneID="&lt;%# me.WindowsTimeZoneID %&gt;" IsRequired="false" /&gt; </code></pre> <p>As you can see, my Composite control is for handling DateTimeOffset values. It all works great unless the DateTimeOffset field [dtoMldRejOn] from the database is NULL, then I get the exception.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload