Introduction
The calendar control is part of the dot net web controls collection. Its in the namespace System.Web.UI.WebControls. It provides an efficient mechanism for the user to to select dates in the desired format.But one of the functionality that we require most of the time, as part of validation is to disable a range of dates. Mostly we weould like to disable past dates so that user wont select them. This can be done with a little bit of tweaking. I will explain this in my article.
The DayRender event :
The most important event for us in this scenario, is the OnDayRender event. This event fires when the calendar is first rendered on the screen. This happens as a loop, wherein it continuously renders each day, one a time.
We have to write our logic in the OnDayRender event hanlder, to disable rendering when the day matches our criteria.
The Code:
In my code, I have a calendar control. I want to block it for all past days as well as next 7 days. I set this value in a local variable,nDaysToBlock.
As you can see from the code, all the action happens in the DayRender event handler.
<code>
protected void myDayRenderMethod(object sener, DayRenderEventArgs e)
{
if (e.Day.Date < (System.DateTime.Now.AddDays(_nDaysToBlock)))
{
e.Day.IsSelectable = false;
e.Cell.Font.Strikeout = true;
}
}
</code>
Here, iam checking if the day being rendered is less than the current day plus number of days to block. i.e, is it less than 7 days from now. In that case, we want to block such a day from being rendered, which is done by making e.Day.IsSelectable as false;
That is all there is to it. You have the desired dates disabled. You can change the font to strike out, so as to easily distinguish them.
The calendar will look as below at runtime, with selected dates disabled.
<formulas /></formulas />
Hope my code snippet was of help to you.
Thanks.