Introduction
This is a simple way to add an extra column to the asp.net calendar control that shows the
week number for each row like illustrated below.
Background
In some contries week numbers is often used and the standard calendar control does not
include the option to show week numbers.
After having experimented with different events of the control I discovered that using javascript
the column could be added very simpel, all though I would have preffered a code-behind
solution.
In my search for a solution I found many request for this, but no sutable solution.
Using the code
The code is simple. I use a javascript function "addWkColumn" to manipulate the table that is
created by the calendar control.
function addWkColumn(tblId, wkStart)
{
var tbl = document.getElementById(tblId);
var tblBodyObj = tbl.tBodies[0];
for (var i=0; i<tblBodyObj.rows.length; i++)
{
if (i==0)
{
tblBodyObj.rows[i].cells[0].colSpan=8;
}
if (i==1)
{
var newCell = tblBodyObj.rows[i].insertCell(0);
newCell.innerHTML = 'wk';
newCell.style.fontSize= '8px';
newCell.style.fontWeight= 'bold';
newCell.style.verticalAlign= 'bottom';
newCell.style.backgroundColor = '#ffffee';
}
if (i >= 2 )
{
var newCell = tblBodyObj.rows[i].insertCell(0);
newCell.innerHTML = wkStart;
wkStart += 1;
newCell.style.fontSize= '8px';
newCell.style.backgroundColor = '#ffffee';
}
}
}
Now all you have to do is to call the javascript function with the table id for the calendar table.
To do this I use the ClientScript.RegisterStartupScript from code behind, to ensure the correct
clientid name and to find the week number for the first week in the shown month.
private void addWeekNumberColumn()
{
DateTime curMonth = Calendar1.VisibleDate;
curMonth = Convert.ToDateTime(curMonth.Year.ToString() + "-" + curMonth.Month.ToString() + "-01");
string jscript = "<script type='text/javascript'> addWkColumn('" + Calendar1.ClientID + "', " + getISOWeek(curMonth).ToString() + ");</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "AddWeeknumbers", jscript);
}
private int getISOWeek(DateTime day)
{
return System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(day, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
Now all you have to do is to call the addWeekNumberColumn() function from the page_load
event of the page.
Points of Interest
Please note that the javascript function should only be called with a reference to a calendar
control created tableID, as it references cell numbers directly. This is no problem unless you call
it with a different table.
Happy coding!
History
Version 1.0