- // Default.aspx
- <%@ Register Src="~/xCalendar.ascx" TagName="xCalendar" TagPrefix="x" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Custom Calendar</title>
- <style>
- .today { background-color:#ccc; }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <x:xCalendar ID="Calendar" TodayCssClass="today" DayTitleFormat="FullTitle" runat="server" />
- </div>
- </form>
- </body>
- </html>
- //xCalendar.ascx
- <%@ Import Namespace="System.Text" %>
- <%@ Control Language="C#" ClassName="xCalendar" %>
- <script language="c#" runat="server">
- private DateTime _Date = DateTime.Now;
- private TitleFormat _TitleFormat = TitleFormat.FullTitle;
- public DateTime SelectDate
- {
- set { this._Date = value; }
- get { return this._Date; }
- }
- public TitleFormat DayTitleFormat
- {
- set { this._TitleFormat = value; }
- get { return this._TitleFormat; }
- }
- public string TodayCssClass
- {
- set;
- get;
- }
- protected override void Render(HtmlTextWriter writer)
- {
- base.Render(writer);
- StringBuilder Control = new StringBuilder();
- int DaysInMonth = DateTime.DaysInMonth(SelectDate.Year, SelectDate.Month);
- string FirstDayOfMonth = DateTime.Parse(SelectDate.Year + "-" + SelectDate.Month + "-01").DayOfWeek.ToString();
- int DayWeekNum = 0;
- string[] Days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
- Control.Append("<table border=1><tr>");
- for (int i =0; i < Days.Length; i++)
- {
- if (this.DayTitleFormat == TitleFormat.FullTitle)
- {
- Control.Append("<td>" + Days[i] + "</td>");
- }
- else if (this.DayTitleFormat == TitleFormat.ShortTitle)
- {
- Control.Append("<td>" + Days[i].Substring(0, 3) + "</td>");
- }
- else
- {
- Control.Append("<td>" + Days[i].Substring(0, 1) + "</td>");
- }
- if (Days[i] == FirstDayOfMonth)
- {
- DayWeekNum = i;
- }
- }
- Control.Append("</tr><tr>");
- for (int i =0; i < DayWeekNum; i++)
- {
- Control.Append("<td> </td>");
- }
- for (int i = 1; i <= DaysInMonth; i++)
- {
- string strTodayCssClass = "";
- if (SelectDate.Day == i)
- {
- strTodayCssClass = " class=\"" + TodayCssClass + "\"";
- }
- if (DayWeekNum < 7)
- {
- Control.Append("<td" + strTodayCssClass + ">" + i + "</td>");
- DayWeekNum++;
- }
- else
- {
- Control.Append("</tr><td" + strTodayCssClass + ">" + i + "</td>");
- DayWeekNum = 1;
- }
- }
- for (int i = 0; i < (7-DayWeekNum); i++)
- {
- Control.Append("<td> </td>");
- }
- Control.Append("</tr></table>");
- writer.Write(Control.ToString());
- }
- public enum TitleFormat
- {
- FullTitle,
- ShortTitle,
- SingleCharTitle
- }
- </script>
ASP.Net - Custom Calendar Control
This simple code snippet shows how to create a custom calendar control using a Web User Control.
No comments:
Post a Comment