DateTimeControl Saving Blank Values

Karine Bosch’s blog post on the SharePoint DateTimeControl is really great for understanding how to use this control in your custom web parts or application pages. It’s probably one of the only really good resources out there on this control.

So to summarize, the SelectedDate property let’s us know what date the user has selected. However, if the user didn’t enter a date the SelectedDate property returns Today’s date. Huh?

This presents a problem because of form submission. Let’s review a scenario where this causes issues:

  1. User enters a date in a DateTimeControl: April 3, 2011.
  2. User submits. Date is saved as April 3, 2011 in the SharePoint DateTime field.
  3. User loads form, and clears out the date in the DateTimeControl and hits submit.
  4. Date is saved as April 1, 2011 (Today’s date).

We don’t want it saved as Today’s date, we want it saved as blank. To get around this, we constantly have to check whether a value is entered using the IsDateEmpty property, and if so, handle the save appropriately. See my code sample below for an example of this.

if (!dateControl.IsDateEmpty)
{
    item["Deadline"] = dateControl.SelectedDate;
}
else
{
    item["Deadline"] = null;
}

, ,

4 Responses to “DateTimeControl Saving Blank Values”

  1. mizark April 25, 2011 at 10:22 am #

    How do I do this if I am using Sharepoint Designer 2007 and can’t take advatage of the code behind pages? (.cs files) Thanks for the great post.

    Thanks in advance.

  2. shereen April 25, 2011 at 1:22 pm #

    Hi Mizark,

    Can you give me a little more information on how you’re using SharePoint designer and what your scenario looks like? Is it a custom form? Is it a new, edit or disp form? What is the behavior when you save a blank DateTimeControl? Is it saving Today’s date?

  3. mizark April 25, 2011 at 2:12 pm #

    Hi Shereen,

    I have a multiple item dataview that is pulling data from a database and I have also added the insert and edit components to the dataview as well. In the insert and edit sections of the screen I want to use the Sharepoint:DateTimeControl for my date fields. The problem is whenever I save the edit or insert form and leave these fields blank with this control in place it defaults to todays date. I want it to be an empty string or just left blank.

    Thanks again,
    Mizark

  4. Thom June 7, 2013 at 6:57 am #

    I have the same problem of the mizark. =/

Leave a Reply