Overview
By default, Calendar control won't allow you to restrict the selectable date range. However, we can achieve this by doing two things:
- Restrict user from navigating to a month outside the range
- Restrict user from selecting a day outside the range
Reference
Visual Studio .NET - restrict date range in Calendar - eggheadcafe
Disable calendar day select link - eggheadcafe
Steps
Restrict user from navigating to a month outside the range
To achieve this, we can set the "NextMonthText" and "PrevMonthText" fields of the Calendar control to hide the link navigating to next or previous month.
Code Snippet:
protected void Cal_PreRender(object sender, EventArgs e)
{
if (Cal.VisibleDate.Year > 2009 || (Cal.VisibleDate.Year == 2009 && Cal.VisibleDate.Month >= 12))
{
Cal.NextMonthText = string.Empty;
}
else
{
Cal.NextMonthText = ">";
}
if (Cal.VisibleDate.Year < 2000 || (Cal.VisibleDate.Year == 2000 && Cal.VisibleDate.Month <= 1))
{
Cal.PrevMonthText = string.Empty;
}
else
{
Cal.PrevMonthText = "<";
}
}
Restrict user from selecting a day outside the range
This can be achieved by controlling the "IsSelectable" field in the "onDayRender" event handler of the Calendar.
Code Snippet:
protected void Cal_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date.Year == 2009)
{
e.Day.IsSelectable = false;
}
}