Highlight a date range in asp:Calender

Sometimes we need to highlight a selected date range in asp:Calender control. Here is how it’s done.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
<head id="Head1" runat="server">

    <form id="form1" runat="server">
    <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

We get the difference as a TimeSpan and highlight the dates one by one by going through a loop. In this example I’m highlighting the dates from 2012/08/11 to today’s date.

Code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication1
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            DateTime startDate = Convert.ToDateTime("2012/08/11");
            DateTime endDate = DateTime.Now;
            TimeSpan difference = endDate.Date - startDate.Date;

            Calendar1.SelectedDates.Clear(); //Clear previously selected dates, if any
            for (int i = 0; i <= difference.Days; i++)
                Calendar1.SelectedDates.Add(startDate.AddDays(i)); //Highlight the dates

No comments: