I have a List called “Project Status Reports”, which is a List populated with List Items based on the “Project Status Report” content type. Since each status report is associated with a given “Project” in my other “Projects” list, I wanted to write a custom User Control to be put in my CONTROLTEMPLATES folder, which could be used to render the form for the “New” or “Edit” view [See how to do it here], and I wanted this form to have some of its fields pre-populated based on fields from its associated List Item in the Projects list. (I’m doing this to “denormalize” my site, so-to-speak. I want to be able to do a CAML query to retrieve everything on the site according to its project start date and end date. I didn’t want to have to retrieve Projects for a time frame, and then have to link to the status reports. If the dates are stored with the status f reports, they’ll get returned with my CAML query.)
Specifically, I wanted to populate the “Project Start Date” in my form. In my ASCX control, I droped the following control:
<SharePoint:FormField runat="server" ID="ProjectStartDateField" FieldName="ProjectStartDate"/>
For many of the fields that are textual, I was able to prepopulate their value simply by setting the FormField.ItemFieldValue of the SharePoint Form Field control. For my form field, which has a DateTimeField underlying it, setting the ItemFieldValue had no effect; the date was simply not set, or defaulted to today’s date.
I then moved on to set the Value of the FormField. For other form fields on my page, such as a Lookup field, this seemed to do the trick. However, when I tried to set the value of the DateTimeField, I got an error, regardless of whether I was trying to set it to a DateTime or a String value.
Next, I tried to convert my time to a SharePoint-friendly format, using the SPUtilities.CreateISO8601DateTimeFromSystemDateTime method. Unfortunately, when I tried that, I got an error saying, “The specified cast is not valid.” I was at the end of my rope.
Inside the DateTimeField control is a DateTimeControl control that’s used to actual render the control. This control didn’t seem to have a “Value” property. However, I eventually stumbled on the DateTimeControl.SelectedDate property. I was finally able to set the value of the control by setting this property. My code finally looked like this:
DateTimeControl dtc = (DateTimeControl)ProjectStartDateField.Controls.Controls.Controls; dtc.SelectedDate = (DateTime)projectItem["Project Start Date"];
It’s frustrating when you spend hours on a problem and the solution is so simple. [Sigh] Hopefully this post will save someone out there some time.