ASP.NET FAQ - Calendar

How can I use a Calendar Control to show specific dates highlighted and display relevant data for that date
<asp:Calendar id='Calendar1' OnDayRender ='CalDayRender' runat='server'></asp:Calendar>
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	’Fill the DataSet 
End Sub

Protected Sub CalDayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)
	Dim strName As New StringBuilder
	strName.Append('
')
	Dim theDay As DateTime = e.Day.Date
	Dim sql As String = 'hiredate=’' + DateTime.Parse(theDay.ToString('d')) + '’ '
	Dim dr As DataRow() = ds.Tables(0).Select(sql)
	Dim drRow As DataRow
	For Each drRow In dr
	            strName.Append('’<a href=empdetails.aspx?id=' + drRow('Employeeid').ToString() + '>' + drRow('FirstName').ToString() + ' ' + drRow('LastName').ToString() + '</a><br>’')
	            e.Cell.BackColor = Color.Teal
	            e.Cell.ForeColor = Color.Wheat
        	Next drRow
	strName.Append('')
	e.Cell.Controls.Add(New LiteralControl(strName.ToString()))
End Sub ’CalDayRender

C#

DataSet ds  ;
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	//Populate the DataSet
}

protected void CalDayRender(object sender, DayRenderEventArgs e)
{
	StringBuilder strName = new StringBuilder();
	strName.Append('
');
	DateTime theDay = e.Day.Date;
	string sql ='hiredate=’' + DateTime.Parse ( theDay.ToString('d')) + '’ ';
	DataRow [] dr = ds.Tables[0].Select(sql);
	foreach(DataRow drRow in dr)
	{
		strName.Append('’<a href=empdetails.aspx?id=' + drRow('Employeeid').ToString() + '>' + drRow('FirstName').ToString() + ' ' + drRow('LastName').ToString() + '</a><br>’')
		e.Cell.BackColor = Color.Teal;
		e.Cell.ForeColor = Color.Wheat;
	}
	strName.Append('');
	e.Cell.Controls.Add(new LiteralControl(strName.ToString()));
}
Permalink
How can I display the calendar control in different languages according to the navigator culture

Use namespace

  • System.Threading
  • System.Globalization
<p>
<asp:dropdownlist id='DropDownlist1' runat='server'></asp:dropdownlist></p>
<p>
<asp:Button id='Button1' runat='server' Text='Button'></asp:Button></p>
<asp:calendar id='Calendar1' runat='server'></asp:calendar>

VB.NET

Dim userLang() As String
Dim strLang As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	userLang = Request.UserLanguages
        	ViewState('userLanguage') = userLang(userLang.GetUpperBound(0))
        	If ViewState('userLanguage') = '' Then
            		ViewState('userLanguage') = 'en-US'
        	End If
        	Dim ci As CultureInfo
        	For Each ci In CultureInfo.GetCultures(CultureTypes.AllCultures)
            		If Not ci.IsNeutralCulture Then
                		DropDownlist1.Items.Add(ci.ToString)
            		End If
        	Next 
        	Dim dtNow As Date = DateTime.Now
        	strLang = ViewState('userLanguage')
        	Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
        	Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
        	Calendar1.SelectedDate = dtNow
        	Calendar1.VisibleDate = dtNow
End Sub

Private Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged
	strLang = ViewState('userLanguage')
        	Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
        	Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
	strLang = DropDownlist1.SelectedItem.Text
        	ViewState('userLanguage') = strLang
        	Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
        	Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
End Sub

C#

string[] userLang;
string strLang;
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	userLang = Request.UserLanguages;
	ViewState['userLanguage'] = userLang[userLang.GetUpperBound(0)];
	if( ViewState['userLanguage'].ToString () == '' )
	{
		ViewState['userLanguage'] = 'en-US';
	}
         	foreach(CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
	{
		if(!ci.IsNeutralCulture)
		{
			DropDownlist1.Items.Add(ci.ToString());
		}
	}
        	DateTime dtNow   = DateTime.Now;
        	strLang =(string) ViewState['userLanguage'];
        	Thread.CurrentThread.CurrentUICulture = new CultureInfo(strLang, false);
        	Thread.CurrentThread.CurrentCulture =new CultureInfo(strLang);
        	Calendar1.SelectedDate = dtNow;
        	Calendar1.VisibleDate = dtNow;
}

private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
	strLang =(string) ViewState['userLanguage'].ToString ();
        	Thread.CurrentThread.CurrentUICulture = new CultureInfo(strLang, false);
        	Thread.CurrentThread.CurrentCulture = new CultureInfo(strLang);
}

private void Button1_Click(object sender, System.EventArgs e)
{
	 strLang = DropDownlist1.SelectedItem.Text;
	 ViewState['userLanguage'] = strLang;
        	Thread.CurrentThread.CurrentUICulture =new CultureInfo(strLang, false);
        	Thread.CurrentThread.CurrentCulture = new CultureInfo(strLang);
}
Permalink
How can I set the Selection of the Calendar Control to date or week or month

Set the SelectionMode =DayWeekMonth

You can set it to any of the following:

  • Day
  • DayWeek
  • DayWeekMonth
  • None
Permalink
How can I change the month and Weekdays to Japanese characters for a Calendar Control

Set the Culture= ‘ja-JP’ for the Page.

  • ASP.NET pages support Culture and UICulture attributes to support independent localized pages.
  • Controls on pages can pick the culture of the page and can render culture-dependent content.
Permalink
How to display multiple dates selected in Calendar Control

Set the SelectionMode property of Calendar Control to DayWeek/ DayWeekMonth.

Code for the OnSelectionChanged as follows:

VB.NET

Dim day As DateTime
Dim strval As String
For Each day In Calendar1.SelectedDates
	strval += (day.Date.ToShortDateString() & '<br>')
Next
Response.Write(strval)

C#

string strval='' ;
foreach (DateTime day in Calendar1.SelectedDates)
{
	strval += (day.Date.ToShortDateString() + '<br>');
}
Response.Write(strval);
}
Permalink
How to Programmatically change backgroundcolor of a Calendar Control using Dropdown List
<asp:Calendar id='Calendar1' style='Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 48px' runat='server'></asp:Calendar>
<asp:DropDownList id='DropDownList1' style='Z-INDEX: 102; LEFT: 40px; POSITION: absolute; TOP: 24px'
	runat='server' AutoPostBack='True'>
	<asp:ListItem Value='Red'>Red</asp:ListItem>
	<asp:ListItem Value='Green'>Green</asp:ListItem>
	<asp:ListItem Value='Blue'>Blue</asp:ListItem>
</asp:DropDownList>

VB.NET

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
	Dim colorName As String = DropDownList1.SelectedItem.Text
	Dim objBackColor As System.Drawing.Color = System.Drawing.Color.FromName(colorName)
	Calendar1.BackColor = objBackColor
End Sub

C#

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
	string  colorName   = DropDownList1.SelectedItem.Text;
	System.Drawing.Color objBackColor    = System.Drawing.Color.FromName(colorName);
	Calendar1.BackColor = objBackColor;
}
Permalink
How to change the Calendar Dates using a Dropdownlist
<asp:DropDownList id='ddlMonth' style='Z-INDEX: 101; LEFT: 64px; POSITION: absolute; TOP: 24px' runat='server'
	AutoPostBack='True'></asp:DropDownList>
<asp:Label id='Label1' style='Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 24px' runat='server'>Month</asp:Label>
<asp:DropDownList id='ddlYear' style='Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 24px' runat='server'
	AutoPostBack='True'></asp:DropDownList>
<asp:Label id='Label2' style='Z-INDEX: 104; LEFT: 152px; POSITION: absolute; TOP: 24px' runat='server'>Year</asp:Label>
<asp:Calendar id='Calendar1' style='Z-INDEX: 105; LEFT: 16px; POSITION: absolute; TOP: 72px' runat='server'></asp:Calendar>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’ Put user code to initialize the page here
	If Not Page.IsPostBack Then
		’Populate month in the dropdownlist
	           	Dim strMonth As String = ''
		Dim i As Integer
		            For i = 1 To 12
		                If i.ToString().Length < 2 Then
				strMonth = '0' + i.ToString()
			                ddlMonth.Items.Add(New ListItem(strMonth, strMonth))
		                Else
	                	ddlMonth.Items.Add(New ListItem(strMonth, strMonth))
  		              	End If
		            Next

	            	ddlMonth.Items.FindByValue(DateTime.Now.ToString('MM')).Selected = True
            		’Populate year in the dropdownlist
		Dim j As Integer
		For j = 1900 To 2050
		                ddlYear.Items.Add(New ListItem(j.ToString(), j.ToString()))
		Next
		ddlYear.Items.FindByText(DateTime.Now.ToString('yyyy')).Selected = True
	End If
End Sub ’Page_Load

Private Sub ddlMonth_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlMonth.SelectedIndexChanged
	        SetCalendarDate()
End Sub ’ddlMonth_SelectedIndexChanged

Private Sub ddlYear_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlYear.SelectedIndexChanged
  	      SetCalendarDate()
End Sub ’ddlYear_SelectedIndexChanged

Sub SetCalendarDate()
  	Dim dtNewDate As DateTime
	dtNewDate = DateTime.Parse((Int16.Parse(ddlMonth.SelectedItem.Text) & '/1/' & Int16.Parse(ddlYear.SelectedItem.Text)))
	Calendar1.TodaysDate = dtNewDate
End Sub ’SetCalendarDate

C#

private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		//Populate month in the dropdownlist
		string strMonth='';
		for(int i = 1 ;i<=12;i++)
		{
			if (i.ToString().Length <2 )
			{
				strMonth ='0' + i.ToString ();
				ddlMonth.Items.Add (new ListItem(strMonth,strMonth )) ;
			}
			else
			{
				ddlMonth.Items.Add (new ListItem(strMonth,strMonth )) ;
			}
		}
		ddlMonth.Items.FindByValue (  DateTime.Now.ToString ('MM')).Selected =true;    
		//Populate year in the dropdownlist
		for(int j = 1900 ;j<=2050;j++)
		{
			ddlYear.Items.Add (new ListItem(j.ToString(),j.ToString () )) ;
		}
		ddlYear.Items.FindByText (DateTime.Now.ToString ('yyyy')).Selected =true;
	}
}

private void ddlMonth_SelectedIndexChanged(object sender, System.EventArgs e)
{
	SetCalendarDate();
}
private void ddlYear_SelectedIndexChanged(object sender, System.EventArgs e)
{
	SetCalendarDate();
}
void SetCalendarDate()
{
	DateTime dtNewDate; 
	dtNewDate =DateTime.Parse (Int16.Parse(ddlMonth.SelectedItem.Text) + '/1/' + Int16.Parse( ddlYear.SelectedItem.Text));
	Calendar1.TodaysDate=dtNewDate ;
}
Permalink
How to clear the Calendar Control Selection

VB.NET

Calendar1.SelectedDate =new DateTime()

C#

Calendar1.SelectedDate =new DateTime();
Permalink
How to display full day names in a Calendar Control

Set the DayNameFormat= Full for the Calendar Control

Permalink
How can I use a Calendar Control in readonly mode. i.e no links for the day and month cells.

In the DayRender Event of calendar Control

VB.NET

If e.Day.IsOtherMonth Then
            e.Cell.Text = ' '
Else
            e.Cell.Text = e.Day.DayNumberText
End If

C#

if (e.Day.IsOtherMonth )
{
            e.Cell.Text = ' ';
}
else
{ 
         e.Cell.Text = e.Day.DayNumberText;
}
Permalink
How to highlight today’s date in Calendar Control in different color

In Calendar DayRender Event

VB.NET

If e.Day.IsToday Then
	e.Cell.ForeColor = Color.Blue
	e.Cell.BackColor = Color.Pink
End If

C#

if (e.Day.IsToday) 
{
            e.Cell.ForeColor = Color.Blue;
            e.Cell.BackColor = Color.Pink;
}
Permalink
How to hide ‘other months’ in a Calendar Control

In the Calendar DayRender Event

VB.NET

If e.Day.IsOtherMonth = True Then
	e.Cell.Text = ''
End If

C#

if (e.Day.IsOtherMonth = true)
{
            e.Cell.Text = '';
}
Permalink
How to hide the WeekDay Header in the Calendar control

In the Calendar PreRender Event

VB.NET

Calendar1.ShowDayHeader = False

C#

Calendar1.ShowDayHeader = false;
Permalink
How to reset the selected date in the calendar control?

VB.NET

Calendar1.VisibleDate = DateTime.Today 
Calendar1.SelectedDates.Clear()

C#

Calendar1.VisibleDate = DateTime.Today;
Calendar1.SelectedDates.Clear();
Permalink