SharePoint DateTime Control
Posted by chrissyz on July 9, 2009
SharePoint brings its own controls and DateTime control is one of them. You can definitely leverage it in your web parts and custom aspx pages. The control is located in the Microsoft.SharePoint.WebControls namespaces.
How to define it? First you need to add the following directive at the top of your application page:
<%@ Register TagPrefix=”SharePoint” Namespace=”Microsoft.SharePoint.WebControls” Assembly=”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
And then place the control in your page
<SharePoint:DateTimeControl runat=”server ID=”dtcDateTime”/>
Please notes that above is just a basic definition, for detailed properties, please check out this link:
How to validate it?
<SharePoint:DateTimeControl runat=”server ID=”dtcDateTime”/>
<asp:CompareValidator ID=”valDateTime” runat=”server”
ForeColor=”Red”
ControlToValidate=”dtcDateTime$dtcDateTimeDate”
Type=”Date”
Operator=”DataTypeCheck”
ErrorMessage=”please enter a valid date” />
How to set a default value to it?
dtcDateTime.SelectedDate = new DateTime();
Check this link for the overloads:
http://msdn.microsoft.com/en-us/library/system.datetime.datetime.aspx
Important notice:
There is a Microsoft bug in SharePoint DateTime Control.
This DateTimeControl loses state during postbacks, specifically of the hour.
I struggled a bit to get this work around because it doesn’t work even if I put enableviewstate=”true” in the control.
However I happened to get this work by adding this line of code in a event that caused the postback. It could be any method/Event, in my case, it is SelectedIndexChanged event:
if (dtcDateTime< DateTime.Today)
{
//Don’t do anything
}
Just be doing this, it maintains the value of the control during postback.




Djheath said
You’re a star! I’ve been trying to solve this problem for ages! Thanks.