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:
- User enters a date in a DateTimeControl: April 3, 2011.
- User submits. Date is saved as April 3, 2011 in the SharePoint DateTime field.
- User loads form, and clears out the date in the DateTimeControl and hits submit.
- 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; } |