How To Conditionally Disable Dates In Calendar Control?
Standard Calendar control is very useful and has its important place on Visual Studio toolbox. Very often, developers need to allow only specific time ranges and disable others. For example, if your web application need to save hotel reservation then it will accept only future dates. Otherwise, if you want for example to search archive posts in blog application then application will allow only past dates to be selected.
All dates in Calendar control are enabled by default. To disable certain dates, you need to use DayRender event, you can do it with code like this:
[ C# ]
// We
need this namespace
using
System.Drawing;
public
partial class
DefaultCS : System.Web.UI.Page
{
protected void
Calendar1_DayRender(object sender,
System.Web.UI.WebControls.DayRenderEventArgs
e)
{
// Select all dates in the past
if (e.Day.Date < System.DateTime.Today)
{
// Disable date
e.Day.IsSelectable = false;
// Change color of disabled date
e.Cell.ForeColor
= Color.Gray;
}
}
}
[ VB.NET ]
' We
need this namespace
Imports
System.Drawing
Partial
Class _Default
Inherits System.Web.UI.Page
Protected Sub
Calendar1_DayRender(ByVal sender
As Object,
ByVal e As
System.Web.UI.WebControls.DayRenderEventArgs) Handles
Calendar1.DayRender
'
Select all dates in the past
If
e.Day.Date < System.DateTime.Today Then
'
Disable date
e.Day.IsSelectable = False
'
Change color of disabled date
e.Cell.ForeColor
= Color.Gray
End
If
End Sub
End
Class
Of course, you can add more than one condition in DayRender event function and change different things for different dates. For example, depending of your needs, some dates could be disabled, some other dates could be pre selected, some important dates can have different style etc. I hope this tutorial was helpful for you.
Happy programming!
Related articles:
1. ControlState Property Demystified
2. Debugging with "Stepping" and "Data Viewing" features
3. Conditional Values And Styles In GridView