Tuesday, December 9, 2008

ASP.Net Calendar control

Following are the steps to use ASP.Net calendar control in a web page:

1) Add <asp:Calendar ... > control tag in your web page.

HTML code:



<table>
<tr>
<td>
<asp:TextBox ID="txtDate" runat="server" Width="300px"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnDate" runat="server"
Text="..." OnClick="btnDate_Click"></asp:Button>
</td>
</tr>
<tr>
<td>
<asp:Calendar ID="calendar" runat="server" OnDayRender="OnDayRender"
BackColor="#ffffff" Width="300px" Height="300px" Font-Size="14px"
NextPrevFormat="shortmonth" DayNameFormat="firsttwoletters"
Visible="False" OnSelectionChanged="calendar_SelectionChanged">

<TodayDayStyle ForeColor="White" BackColor="Black"></TodayDayStyle>
<NextPrevStyle Font-Size="14px" Font-Bold="True"
ForeColor="#333333"></NextPrevStyle>
<DayHeaderStyle Font-Size="14px" Font-Bold="True"></DayHeaderStyle>
<TitleStyle Font-Size="16px" Font-Bold="True"
BorderWidth="2px" ForeColor="#000055"></TitleStyle>
<OtherMonthDayStyle ForeColor="#CCCCCC"></OtherMonthDayStyle>

</asp:Calendar>
</td>
<td>
</td>
</tr>
</table>



2) As visible property of calendar control is set to false, so on button click event set calendar's visible property to true and also set the selected date of calendar from the textbox.

CSharp (C#) code:


protected void btnDate_Click(object sender, EventArgs e)
{
try
{
if (txtDate.Text.Trim() != "")
calendar.SelectedDate = Convert.ToDateTime(txtDate.Text);
}
catch
{ }

calendar.Visible = true; //showing the calendar.
}




3) Add code to handle the SelectionChanged event of calendar control.

CSharp (C#) code:


protected void calendar_SelectionChanged(object sender, EventArgs e)
{
//Displaying the selected date in TextBox
txtDate.Text = calendar.SelectedDate.ToString("d");
calendar.Visible = false; //hiding the calendar.
}




4) Now to disable the earlier/previous date selection in caledar control, handle OnDayRender event of Calendar control.

CSharp (C#) code:


protected void OnDayRender(Object sender, DayRenderEventArgs e)
{
e.Day.IsSelectable = (e.Day.Date >= DateTime.Today);
//e.Day.IsSelectable = (e.Day.Date >= DateTime.Now);
}




Following is the snapshot of Calendar control in a web page :

4 comments:

R.B said...

thanks you Avinash good code for calender

R.B said...

thanks for calender

santhakumar said...

Thanks for lot.. it is really helpful article

Bhushan Bhasme said...

thanks avinash..bu if i add textbox below the textbox for calendar and when i click on button which is given to pop up the calendar then it misplace the below textbox please give the solution
hanking you

Google