Trouble setting SelectedDate on the ASP.Net Calendar Control

Ok, I just discovered this. After searching the internet for the solution I didn’t find anything, so I thought I should blog it so people don’t waste as much time as I just did trying to figure it out.

I have an ASP.Net Calendar control. I needed to set the SelectedDate in the code behind to the current date. My first instinct was to use MyCalendar.SelectedDate = DateTime.Now. Should work, right? Wrong!

Apparently the Calendar control gets confused because DateTime.Now contains the time portion as well as the date portion. So, you have to do DateTime.Today instead.

But, even that doesn’t work completely. That sets the data binding for the control, but doesn’t actually set the value. You then have to do Page.DoBinding() in order for it all to work.

So, in the end, this was the code that I had to use:

       protected void Page_Load(object sender, EventArgs e)
                if (!IsPostBack)
                    BeginCalendar.SelectedDate = DateTime.Today.AddDays(-1);
                    EndCalendar.SelectedDate = DateTime.Today;
            catch (Exception ex)

As a side note, the ASP.Net Calendar control is terrible for more reasons than just this. Every click on the control results in a post back in order to redraw the control with the new selected date. A much better solution is to find a good Javascript calendar control. But, this is an internal web app that needs to be done quickly, so I supposed I’m sticking with this one.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s