Click here to Skip to main content
15,889,877 members
Articles / Programming Languages / C#
Tip/Trick

Disable Future / Past Dates in Calendar - .NET Applications

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
12 May 2014CPOL 13.6K   3   3
Disable Future / past dates in Calendar - .NET Application

Introduction

This tip will help you disable future or past dates from a calendar in .NET application.

Background

It is a prerequisite to have knowledge of Calendar control in .NET.

Using the Code

Drag a Calendar Control from the Tool box of your design page.

Your aspx code will look like below.

Specify event OnDayRender event in your aspx code. Add a name to the event.

ASP.NET
<asp:Calendar ID="CalendarID" runat="server" DatePickerMode="true" 
OnDayRender="Calendar1_DayRender" onselectionchanged="Calendar_SelectionChanged">
</asp:Calendar> 

You need to add the event in your code behind file.

The below code will disable all the future dates from the current date.

C#
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.Date > DateTime.Today)
        {
            e.Day.IsSelectable = false;
        }
    }

The below code will disable all the past dates from the current date.

C#
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
       {
           if (e.Day.Date < DateTime.Today)
           {
               e.Day.IsSelectable = false;
           }
       }

Happy coding! :)

Points of Interest

This is better than throwing an error on future/past date selection. :)

History

  • 12th May, 2014: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNice Simon! Pin
Volynsky Alex12-May-14 8:07
professionalVolynsky Alex12-May-14 8:07 
GeneralThoughts Pin
PIEBALDconsult12-May-14 6:11
mvePIEBALDconsult12-May-14 6:11 
GeneralRe: Thoughts Pin
Tejal S12-May-14 18:43
Tejal S12-May-14 18:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.