Add LinkButton to Calendar Cell ASP.NET

1. January 2009 01:06

Well I was looking for to click on a linkbutton in an calendar control that I was adding dynamically.  Now as first, logically I thought I could just add a link button dynamically on the DayRender event for the calendar control.  However, according to some reading I noticed that you can't add any controls that require an event to the calendar control.  This would includes items such as a LinkButton, which I was hoping I could use and just wire up the event when adding it dynamically :)  Oh so wishful thinking.  Well it turns out this problem is not too difficult to solve.  You'll notice that the calendar control already converts the days to a link and does a post back to the page. So obviously this is happening somehow.  If you hover your mouse over one of the days it will looks something like this:

javascript:__doPostBack(controlID, '3276')

So here is how you solve this problem and add the ability to provide the way for a user to click on something besides the day.  I chose to use a HyperLink and add that dynamically on the DayRender event as shown below:

 protected void calEvents_DayRender(object sender, DayRenderEventArgs e)
        e.Cell.Controls.Add(new LiteralControl("<br />"));

        HyperLink lnkEvent = new HyperLink();

        lnkEvent.Text = "Your Text Here";
        lnkEvent.Font.Size = FontUnit.Parse("8");
        lnkEvent.Font.Bold = false;
        lnkEvent.Font.Name = "Arial";
        lnkEvent.NavigateUrl = e.SelectUrl;
        lnkEvent.ForeColor = System.Drawing.Color.Navy;
        lnkEvent.Font.Underline = false;


The part that is bolded is what allows the hyperlink to act as the same as the link the control creates itself for the calendar.  If you do a view source after the page has rendered you'll notice the days are just links and nothing more.

Again, I couldn't a good posting on this concept so hopefully this will help others as well.

And yes I know it's New Years Eve, but I had to get some coding done for our product Club Dynamix.  Not to say that I'm not enjoying myself :)



blog comments powered by Disqus

My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

John On Twitter