Customizing the Calendar Control
This post is all about customizing the calendar control to display certain date range values in various forms like in different color, enable/disable those date range values like that.
I am considering the scenario of disabling the weekend dates and specific dates, say from may 1, 2008 to may 10, 2008. This code can be embedded in the Day_Render event of the calendar control.
HTML Syntax of the Calendar Control
<asp:Calendar ID="myCal" runat="server" Caption="My Calendar" CaptionAlign="Top"
CellPadding="2" CellSpacing="2" ShowTitle="true" OnDayRender="myCal_DayRender"
Font-Names="verdana" Font-Size="Small">
<DayHeaderStyle BackColor="CadetBlue" HorizontalAlign="center"
VerticalAlign="Middle" />
<WeekendDayStyle BackColor="gray"></WeekendDayStyle>
<SelectedDayStyle BackColor="BurlyWood" ForeColor="DarkBlue" Font-Names="Calibri"
Font-Bold="true" />
</asp:Calendar>
Code Behind event for the Calendar Control
protected void myCal_DayRender(object sender, DayRenderEventArgs e)
{
// Change the background color of the days in the month to yellow.
if (!e.Day.IsOtherMonth && !e.Day.IsSelected)
e.Cell.BackColor = System.Drawing.Color.AliceBlue;
// Display vacation dates in yellow boxes with purple borders.
Style vacationStyle = new Style();
vacationStyle.BackColor = System.Drawing.Color.Gray;
vacationStyle.ForeColor = System.Drawing.Color.LightGray;
vacationStyle.BorderWidth = 1;
vacationStyle.Font.Strikeout = true;
// Display weekend dates in green boxes.
Style weekendStyle = new Style();
weekendStyle.BackColor = System.Drawing.Color.Gray;
if ((e.Day.Date >= new DateTime(2008, 05, 01)) &&
(e.Day.Date <= new DateTime(2008, 05, 10)))
{
// Apply the vacation style to the vacation dates.
e.Cell.ApplyStyle(vacationStyle);
//e.Cell.Enabled = false;
e.Cell.Text = e.Day.DayNumberText;
}
else if (e.Day.IsWeekend)
{
// Apply the weekend style to the weekend dates.
e.Cell.ApplyStyle(weekendStyle);
e.Cell.Enabled = false;
e.Cell.Text = e.Day.DayNumberText;
}
DateTime myAppointment = new DateTime(DateTime.Today.Year , 05, 26);
if (e.Day.Date == myAppointment)
{
e.Day.IsSelectable = false;
e.Cell.Controls.Add(new LiteralControl("
My Appointment"));
}
else
{
e.Day.IsSelectable = true;
}
}