How to disable dates and prevent from selecting in asp:Calendar controller

My first post in new year. Happy new year everyone!! Smile

Sometimes we need to prevent users from selecting future dates or past dates or some date range. The following example shows how to achieve it in asp:Calendar control.

ASPX code

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
    <asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"></asp:Calendar>

Code behind (C#)

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

namespace Tests
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)


        protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
            if (e.Day.Date.CompareTo(DateTime.Today.AddDays(5)) >0)
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Gray;

In the code behind I’m checking the dates in the calendar on the DayRender event and if the date is more than 5 days after the today’s date, I’m disabling those date in the calendar. I’m adding 5 days to the today’s date (Which means it will get the date of 5 days after the today). Then I’m comparing it with the dates in the calendar control. If the calendar dates are greater than that value (Which means those are future dates than the date from 5 days from today), I’m setting the IsSelectable property to false for those days and setting the ForeColor to Gray. So those days will be disabled on the calendar control.

In short, this calendar control will not let users to select the dates more than 5 days from the today’s date.

1 comment:

Pavithra M said...

It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training in velachery