自制的日历控件,可以在日历上DIY事情,相关于记一些随笔的文字之类的话题,如“1/28 是新年啊”


界面文件代码:
-----------------------------------------------------------------------------------------------------
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Customer_Canlendar.ascx.cs"
    Inherits="Customer_Canlendar" %>
<asp:Calendar ID="CustCalendar" runat="server" BackColor="#FFFFCC" BorderColor="#FFCC66"
    BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"
    ForeColor="#663399" Height="222px" OnDayRender="CustCalendar_DayRender" OnSelectionChanged="CustCalendar_SelectionChanged"
    ShowGridLines="True" Width="340px">
    <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
    <TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
    <SelectorStyle BackColor="#FFCC66" />
    <OtherMonthDayStyle ForeColor="#CC9966" />
    <NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
    <DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
    <TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt" ForeColor="#FFFFCC" />
</asp:Calendar>
Choose.........................................................................<br />
Month:
<asp:DropDownList ID="ddlMonth" runat="server">
</asp:DropDownList>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp;Day:<asp:DropDownList ID="ddlDays" runat="server">
</asp:DropDownList><br />
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:TextBox ID="txtContext" runat="server" Height="107px" TextMode="MultiLine"></asp:TextBox>&nbsp;
<asp:Button ID="btnSave" runat="server" Text="保存" OnClick="btnSave_Click" />


-----------------------------------------------------------------------------------
CS文件代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Customer_Canlendar
/// </summary>
public partial class Customer_Canlendar : System.Web.UI.UserControl
{
    #region Param

    private const string EMPTYSTRING = "";

    private const int monthTotal = 12;

    private const int daysTotal = 31;

    public string _schedule = String.Empty;

    public int _month;

    public int _days;

    String[][] schedules;

    public const string MONTH = "Month";

    public const string DAYS = "Days";

    public const string CONTEXT = "Context";

    #endregion

    #region Property

    public string Schedule
    {
        get
        {
            return _schedule;
        }
        set
        {
            _schedule = value;
        }
    }

    public int Month
    {
        get
        {
            return _month;
        }
        set
        {
            _month = value;
        }
    }

    public int Days
    {
        get
        {
            return _days;
        }
        set
        {
            _days = value;
        }
    }


    #endregion

    #region Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                MonthDataBind();
                DaysDataBind();
                createXmlFile();
                setContext();
            }
        }
        catch { }
    }

    #endregion

    #region CustCalendar_DayRender

    private void setContext()
    {
        schedules = new String[daysTotal][];

        for (int n = 0; n < daysTotal; n++)
            schedules[n] = new String[daysTotal + 1];
       
        //set Context
        ReadXmlFile();

    }

    protected void CustCalendar_DayRender(object sender, DayRenderEventArgs e)
    {
        try
        {
            CalendarDay _calendarDay = ((DayRenderEventArgs)e).Day;
            TableCell _tableCell = ((DayRenderEventArgs)e).Cell;

            if (_calendarDay.IsOtherMonth)
            {
                _tableCell.Controls.Clear();
            }
            else
            {
                string Hol = schedules[_calendarDay.Date.Month][_calendarDay.Date.Day];

                if (Hol != String.Empty)
                    _tableCell.Controls.Add(new LiteralControl("<br>" + Hol));

            }
        }
        catch { }
    }

    #endregion

    #region CustCalendar_SelectionChanged

    protected void CustCalendar_SelectionChanged(object sender, EventArgs e)
    {

    }

    #endregion

    #region MonthDataBind & DaysDataBind

    private void MonthDataBind()
    {
        for (int monthCell = 1; monthCell <= monthTotal; monthCell++)
        {
            this.ddlMonth.Items.Add(monthCell.ToString());
        }
    }

    private void DaysDataBind()
    {
        for (int daysCell = 1; daysCell <= daysTotal; daysCell++)
        {
            this.ddlDays.Items.Add(daysCell.ToString());
        }
    }

    #endregion

    #region CreateXmlFile

    private void createXmlFile()
    {
        bool exist = System.IO.File.Exists(Request.PhysicalApplicationPath + "Schedule.xml");
        if (!exist)
        {
            XmlTextWriter xtw = new XmlTextWriter(Request.PhysicalApplicationPath + "Schedule.xml", System.Text.Encoding.Default);

            xtw.Formatting = Formatting.Indented;

            xtw.WriteStartDocument(false);

            //结果:
            xtw.WriteComment("Schedule Infomation");

            //文档注释 结果:
            xtw.WriteStartElement("Info");

            xtw.WriteEndElement();

            xtw.Flush();
            //释放资源
            xtw.Close();
        }
    }

    #endregion

    #region WriteXmlFile
    /// <summary>
    ///
    /// </summary>
    /// <param name="genreText">段值</param>
    /// <param name="monthXml">月份</param>
    /// <param name="daysXml"></param>
    /// <param name="Context"></param>
    private void writeXmlFile(string genreText, string monthXml, string daysXml, string Context)
    {
        //holidays[1][1] = "New Year's Day";
        XmlDocument xmlDoc = new XmlDocument();

        //Load Xml
        xmlDoc.Load(Request.PhysicalApplicationPath + "Schedule.xml");

        //local Xml's root
        XmlNode root = xmlDoc.SelectSingleNode("Info");//查找<Info>

        XmlElement xe1 = xmlDoc.CreateElement("schedule");
        xe1.SetAttribute("genre", genreText);

        //Write Month to xml
        XmlElement xesub1 = xmlDoc.CreateElement(MONTH);
        xesub1.InnerText = monthXml;
        xe1.AppendChild(xesub1);

        //Write Days to xml
        XmlElement xesub2 = xmlDoc.CreateElement(DAYS);
        xesub2.InnerText = daysXml;
        xe1.AppendChild(xesub2);

        //Write Context to xml
        XmlElement xesub3 = xmlDoc.CreateElement(CONTEXT);
        xesub3.InnerText = Context;
        xe1.AppendChild(xesub3);

        root.AppendChild(xe1);

        //Save to xml's File
        xmlDoc.Save(Request.PhysicalApplicationPath + "Schedule.xml");

    }

    #endregion

    #region EditXmlFile

    /// <summary>
    /// 传入element如果是Month,则可以修改对应的Keys值
    /// </summary>
    /// <param name="element"></param>
    /// <param name="key"></param>
    private void EditXmlFile(string element, string key)
    {
        XmlDocument xmlDoc = new XmlDocument();

        //Load Xml
        xmlDoc.Load(Request.PhysicalApplicationPath + "Schedule.xml");

        //获取Info节点的所有子节点
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("Info").ChildNodes;

        //遍历所有子节点
        foreach (XmlNode xn in nodeList)
        {
            //将子节点类型转换为XmlElement类型
            XmlElement xe = (XmlElement)xn;

            //继续获取xe子节点的所有子节点
            XmlNodeList nls = xe.ChildNodes;

            foreach (XmlNode xno in nls)
            {
                //转换类型
                XmlElement xeo = (XmlElement)xno;
                if (xeo.Name == element)
                {
                    //修改
                    xeo.InnerText = key;
                    break;
                }
            }
        }

        xmlDoc.Save(Request.PhysicalApplicationPath + "Schedule.xml");
    }

    #endregion

    #region DelXmlFile

    private void DelXmlFile(string genreKeys)
    {
        XmlDocument xmlDoc = new XmlDocument();

        //Load Xml
        xmlDoc.Load(Request.PhysicalApplicationPath + "Schedule.xml");

        XmlNodeList xnl = xmlDoc.SelectSingleNode("Info").ChildNodes;

        foreach (XmlNode xn in xnl)
        {
            XmlElement xe = (XmlElement)xn;
            if (xe.GetAttribute("genre") == genreKeys)
            {
                xe.RemoveAll();
            }
        }
        xmlDoc.Save(Request.PhysicalApplicationPath + "Schedule.xml");
    }

    #endregion

    #region ReadXmlFile

    private void ReadXmlFile()
    {
        XmlNodeReader xmlRead = null;

        try
        {
            string nodeName = "";
            string monthReader = "";
            string daysReader = "";
            string otherReader = "";

            XmlDocument xmlDoc = new XmlDocument();

            // 装入指定的XML文档
            xmlDoc.Load(Request.PhysicalApplicationPath + "Schedule.xml");

            // 设定XmlNodeReader对象来打开XML文件
            xmlRead = new XmlNodeReader(xmlDoc);

            // 读取XML文件中的数据,并显示出来
            while (xmlRead.Read())
            {
                //判断当前读取得节点类型
                switch (xmlRead.NodeType)
                {
                    case XmlNodeType.Element:
                        nodeName = xmlRead.Name;
                        break;
                    case XmlNodeType.Text:
                        if (nodeName.Equals(MONTH))
                        {
                            monthReader = xmlRead.Value;
                        }
                        if (nodeName.Equals(DAYS))
                        {
                            daysReader = xmlRead.Value;
                        }
                        if (nodeName.Equals(CONTEXT))
                        {
                            otherReader = xmlRead.Value;
                        }
                        break;
                }
                if (!EMPTYSTRING.Equals(monthReader) && !EMPTYSTRING.Equals(daysReader) && !EMPTYSTRING.Equals(otherReader))
                {
                    schedules[System.Convert.ToInt32(monthReader)][System.Convert.ToInt32(daysReader)] = System.Convert.ToString(otherReader);
                    monthReader = EMPTYSTRING;
                    daysReader = EMPTYSTRING;
                    otherReader = EMPTYSTRING;
                }
            }
        }
        finally
        {
            //清除打开的数据流
            if (xmlRead != null)
                xmlRead.Close();
        }
    }

    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!txtTitle.Text.Equals(Session["TITLE"]) && Session["TITLE"] == null)
        {
            Session["TITLE"] = txtTitle.Text;
            writeXmlFile(Session["TITLE"].ToString(), ddlMonth.SelectedItem.Text, ddlDays.SelectedItem.Text, txtContext.Text);
            ReadXmlFile();
        }
    }
}

原文地址:https://www.cnblogs.com/RuiLei/p/325114.html