Showing posts with label Asp.net Calendar Control. Show all posts
Showing posts with label Asp.net Calendar Control. Show all posts

Saturday, December 10, 2011

Customizing the Calendar control in ASP.NET

Recently I had to work on customizing an ASP.NET Calendar control by adding text to the day cells for my team's Remodelogs project. This proved to be not as straight-forward as I thought so here is what I did in case someone else might want to do the same.


The best place to modify the text in a cell seems to be the DayRender event handler. So the first thing I tried was to just modify the e.Cell.Text property like this:


void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{


e.Cell.Text += “My text”;


}


The main problem was that after adding text to a day cell in the control I wasn't able to select that day by clicking on the day number. Here is what you can do if you still want the select day functionality:


void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
AddTextToDayCell(e, Datetime.Today, “MyText“);






}


void AddTextToDayCell(DayRenderEventArgs e, Datetime d, string text)


{


if(e.Day.Date == d.Date)


{


string ID = ((System.TimeSpan)(e.Day.Date - new DateTime(2000, 1, 1))).Days.ToString();


e.Cell.Text = "" + e.Day.DayNumberText; //assuming the name of the calendar control is Calendar1.

e.Cell.Text +=text;

}

}

If you want your new text to act as a link to some other URL, you could modify the AddTextToCell function as follows:


private void Calendar1_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
AddTextToDayCell(e, DateTime.Today, "MyText", "http://www.msn.com"); //this will add the MyText link to http://www.msn.com to the current day's cell
}

void AddTextToDayCell(DayRenderEventArgs e, DateTime d, string text, string URL)

{

if(e.Day.Date == d.Date)

{

string ID = ((System.TimeSpan)(e.Day.Date - new DateTime(2000, 1, 1))).Days.ToString();

e.Cell.Text = "" + e.Day.DayNumberText;

e.Cell.Text += "
" + text;

}

}

Hope you'll find this helpful. Btw, Microsoft is not liable in any way in case you have any trouble after using this code :)