Customizing Links With The ASP.NET Calendar Control

Wednesday, April 18, 2007 6:26:03 AM

While working on a website for my son I wanted to add a calendar in the sidebar with links to dates that had photos or news articles on it.  I managed to get everything customized except for the links; For some reason the styles just would not apply or it would add style="Color:Black" which was most definitely not what I wanted.  As usual, I Googled away, however I did not find any results to solve this problem.  Time to break apart the control and see how it works.

I was already subscribing to the Calendar's DayRender event to mark the day as being selectable, when looking at the cell's controls referenced by the DayRenderEventArgs, however, I noticed it was a LiteralControl which means very little customization. After sleeping on it I noticed that there was a property on the DayRenderEventArgs called SelectUrl.  This property returns the javascript postback that is used to create the selectable link.

Now, armed with a reference to the table cell and the URL used for the link I decided to stop letting ASP.NET tell me what I wanted and instead told it.  First I cleared the cell's controls, then I created a new HyperLink control, set its CssClass attribute, set its URL to e.SelectUrl, text to the current day and added it to the cell.  Have a look at the code below.

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
      // Do we have any dates in are array?
      if (blogDates != null)
            foreach (DateTime dt in blogDates)
                  if (dt.ToShortDateString() == e.Day.Date.ToShortDateString())
                        // We have a match, format the link
                        e.Day.IsSelectable = true;
                        HyperLink hl = new HyperLink();
                        hl.NavigateUrl = e.SelectUrl;
                        hl.CssClass = "CalLink";
                        hl.Text = e.Day.Date.Day.ToString();


Leave Comment




Are you human? Prove it!