Introduction
This tip will help you disable future or past dates from a calendar in .NET application.
Background
It is a prerequisite to have knowledge of Calendar control in .NET.
Using the Code
Drag a Calendar Control from the Tool box of your design page.
Your aspx code will look like below.
Specify event OnDayRender
event in your aspx code. Add a name to the event.
<asp:Calendar ID="CalendarID" runat="server" DatePickerMode="true"
OnDayRender="Calendar1_DayRender" onselectionchanged="Calendar_SelectionChanged">
</asp:Calendar>
You need to add the event in your code behind file.
The below code will disable all the future dates from the current date.
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date > DateTime.Today)
{
e.Day.IsSelectable = false;
}
}
The below code will disable all the past dates from the current date.
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Today)
{
e.Day.IsSelectable = false;
}
}
Happy coding! :)
Points of Interest
This is better than throwing an error on future/past date selection. :)
History
-
12th May, 2014: Initial post