[asp.net] Select current date by default in ASP.Net Calendar control

Let's say I have an aspx page with this calendar control:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="" ></asp:Calendar>

Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?

This question is related to asp.net calendar

The answer is


If you are already doing databinding:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="<%# DateTime.Today %>" />

Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.


DateTime.Now will not work, use DateTime.Today instead.


DateTime.Now will not work, use DateTime.Today instead.


DateTime.Now will not work, use DateTime.Today instead.


DateTime.Now will not work, use DateTime.Today instead.


I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.

protected void Page_Load(object sender, EventArgs e)
    Calendar1.SelectedDate = DateTime.Today;
}

the previous code did NOT highlight the selection, although it set the SelectedDate to today.

However, to select and highlight the following code will work properly.

protected void Page_Load(object sender, EventArgs e)
{
    DateTime today = DateTime.Today;
    Calendar1.TodaysDate = today;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
}

check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx


I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.

protected void Page_Load(object sender, EventArgs e)
    Calendar1.SelectedDate = DateTime.Today;
}

the previous code did NOT highlight the selection, although it set the SelectedDate to today.

However, to select and highlight the following code will work properly.

protected void Page_Load(object sender, EventArgs e)
{
    DateTime today = DateTime.Today;
    Calendar1.TodaysDate = today;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
}

check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx


Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.


Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.


I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control

dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);
dtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());

I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control

dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);
dtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());

Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      DateTime dt = DateTime.Now.AddDays(-1);
      Calendar1.VisibleDate = dt;
      Calendar1.SelectedDate = dt;
      Calendar1.TodaysDate = dt;
      ...
    }
 }

In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.


Actually, I cannot get selected date in aspx. Here is the way to set selected date in codes:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      DateTime dt = DateTime.Now.AddDays(-1);
      Calendar1.VisibleDate = dt;
      Calendar1.SelectedDate = dt;
      Calendar1.TodaysDate = dt;
      ...
    }
 }

In above example, I need to set the default selected date to yesterday. The key point is to set TodayDate. Otherwise, the selected calendar date is always today.


I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.

These now all work:-

<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>

I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.

These now all work:-

<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>

Questions with asp.net tag:

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Custom Authentication in ASP.Net-Core Custom header to HttpClient request ASP.NET 5 MVC: unable to connect to web server 'IIS Express' IIS Config Error - This configuration section cannot be used at this path Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015 TLS 1.2 in .NET Framework 4.0 The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Adding ASP.NET MVC5 Identity Authentication to an existing project TypeError: $(...).DataTable is not a function The page cannot be displayed because an internal server error has occurred on server How to get the current logged in user Id in ASP.NET Core When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 No connection could be made because the target machine actively refused it 127.0.0.1 @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How can I validate google reCAPTCHA v2 using javascript/jQuery? How to get DropDownList SelectedValue in Controller in MVC How do I enable NuGet Package Restore in Visual Studio? Specified cast is not valid? Display two fields side by side in a Bootstrap Form variable is not declared it may be inaccessible due to its protection level An unhandled exception occurred during the execution of the current web request. ASP.NET How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception System.web.mvc missing How to get JSON object from Razor Model object in javascript SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance How to get current domain name in ASP.NET How to return a file (FileContentResult) in ASP.NET WebAPI Select query to get data from SQL Server NuGet: 'X' already has a dependency defined for 'Y' How can I make window.showmodaldialog work in chrome 37? Selecting multiple columns with linq query and lambda expression onchange event for html.dropdownlist Pass multiple complex objects to a post/put Web API method How to update a claim in ASP.NET Identity?

Questions with calendar tag:

Moment.js get day name from date HTML Input Type Date, Open Calendar by default Check if a given time lies between two times regardless of date Creating java date object from year,month,day How to set time to 24 hour format in Calendar How to get Month Name from Calendar? Get first date of current month in java Specify the date format in XMLGregorianCalendar Getting last day of the month in a given string date How to change TIMEZONE for a java.util.Calendar/Date Java Calendar, getting current month value, clarification needed How to get last month/year in java? Calendar date to yyyy-MM-dd format in java How to subtract X day from a Date object in Java? Display calendar to pick a date in java How to tackle daylight savings using TimeZone in Java last day of month calculation How to convert Calendar to java.sql.Date in Java? How to add minutes to my Date Number of days in particular month of particular year? Show week number with Javascript? How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker Java: Get month Integer from Date How to get complete month name from DateTime What's the right way to create a date in Java? Month name as a string Converting a Date object to a calendar object How to set a reminder in Android? How do I create a link to add an entry to a calendar? Convert String to Calendar Object in Java Calendar Recurring/Repeating Events - Best Storage Method How to set time to a date object in java Why Java Calendar set(int year, int month, int date) not returning correct date? How to add calendar events in Android? Set Date in a single line Date object to Calendar [Java] Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net) How do I create an iCal-type .ics file that can be downloaded by other users? How can I use PHP to dynamically publish an ical file to be read by Google Calendar? Java Date vs Calendar How do I calculate someone's age in Java? Leap year calculation How do I localize the jQuery UI Datepicker? System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime() Why is January month 0 in Java Calendar? Calculate business days Programmatically add custom event in the iPhone Calendar How to handle calendar TimeZones using Java? How to sanity check a date in Java How to subtract X days from a date using Java calendar?