使用ASP.NET日历控件时如何隐藏周末?

时间:2009-02-16 18:29:40

标签: asp.net calendar

有时候在显示日历时,有必要阻止周末日期和当天标题中的周末名称显示,有没有办法使用ASP.NET Calendar control执行此操作?

6 个答案:

答案 0 :(得分:7)

提供控件时,如果不覆盖控件,则无法执行此操作。这样做的一种方法是覆盖OnDayRenderRender方法,以便在将信息发送回客户端之前从输出中删除信息。

以下是渲染时控件的外观屏幕截图:

Example of weekday calendar

以下是一个基本的控件覆盖,演示从控件中删除周末日列。

/*------------------------------------------------------------------------------
 * Author - Rob (http://stackoverflow.com/users/1185/rob)
 * -----------------------------------------------------------------------------
 * Notes
 * - This might not be the best way of doing things, so you should test it
 *   before using it in production code.
 * - This control was inspired by Mike Ellison's article on The Code Project
 *   found here: http://www.codeproject.com/aspnet/MellDataCalendar.asp
 * ---------------------------------------------------------------------------*/
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Xml;

namespace DataControls
{
    /// <summary>
    /// Example of a ASP.NET Calendar control that has been overriden to force
    /// the weekend columns to be hidden on demand.
    /// </summary>
    public class DataCalendar : Calendar
    {
        private bool _hideWeekend;
        private int _saturday;
        private int _sunday;

        /// <summary>Constructor</summary>
        public DataCalendar()
            : base()
        {
            // Default to showing the weekend
            this._hideWeekend = false;
            // Set the default values for Saturday and Sunday
            this.Saturday = 6;
            this.Sunday = 0;
        }

        /// <summary>
        /// Indicate if the weekend days should be shown or not, set to true
        /// if the weekend should be hidden, false otherwise. This field 
        /// defaults to false.
        /// </summary>
        public bool HideWeekend
        {
            get { return this._hideWeekend; }
            set { this._hideWeekend = value; }
        }

        /// <summary>
        /// Override the default index for Saturdays.
        /// </summary>
        /// <remarks>This option is provided for internationalization options.</remarks>
        public int Saturday 
        {
            get { return this._saturday; }
            set { this._saturday = value; }
        }


        /// <summary>
        /// Override the default index for Sundays.
        /// </summary>
        /// <remarks>This option is provided for internationalization options.</remarks>
        public int Sunday 
        {
            get { return this._sunday; }
            set { this._sunday = value; }
        }

        /// <summary>
        /// Render the day on the calendar with the information provided.
        /// </summary>
        /// <param name="cell">The cell in the table.</param>
        /// <param name="day">The calendar day information</param>
        protected override void OnDayRender(TableCell cell, CalendarDay day)
        {
            // If this is a weekend day and they should be hidden, remove
            // them from the output
            if (day.IsWeekend && this._hideWeekend)
            {
                day = null;
                cell.Visible = false;
                cell.Text = string.Empty;
            }
            // Call the base render method too
            base.OnDayRender(cell, day);
        }

        /// <summary>
        /// Render the calendar to the HTML stream provided.
        /// </summary>
        /// <param name="html">The output control stream to write to.</param>
        protected override void Render(HtmlTextWriter html)
        {
            // Setup a new HtmlTextWriter that the base class will use to render
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter calendar = new HtmlTextWriter(sw);
            // Call the base Calendar's Render method allowing OnDayRender() 
            // to be executed.
            base.Render(calendar);
            // Check to see if we need to remove the weekends from the header,
            // if we do, then remove the fields and use the new verison for
            // the output. Otherwise, just use what was previously generated.
            if (this._hideWeekend && this.ShowDayHeader)
            {
                // Load the XHTML to a XML document for processing
                XmlDocument xml = new XmlDocument();
                xml.Load(new StringReader(sw.ToString()));
                // The Calendar control renders as a table, so navigate to the
                // second TR which has the day headers.
                XmlElement root = xml.DocumentElement;
                XmlNode oldNode = root.SelectNodes("/table/tr")[1];
                XmlNode sundayNode = oldNode.ChildNodes[this.Sunday];
                XmlNode saturdayNode = oldNode.ChildNodes[this.Saturday];
                XmlNode newNode = oldNode;
                newNode.RemoveChild(sundayNode);
                newNode.RemoveChild(saturdayNode);
                root.ReplaceChild(oldNode, newNode);
                // Replace the buffer
                html.WriteLine(root.OuterXml);
            }
            else
            {
                html.WriteLine(sw.ToString());
            }
        }
    }
}

答案 1 :(得分:0)

据我所知,你不能,但你可以尝试使用WeekendDayStyle,例如使用display:none设置样式。或者,您可以创建从Calendar继承的自定义控件,并覆盖ether Render,OnDayRender或其他内容。

答案 2 :(得分:0)

我相信您可以处理Day Render事件并隐藏单元格或指定CSS属性以使其不可见或变灰。下面是一个简单的例子,我希望这会有所帮助。

protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
{

  e.Cell.Visible = False;
  // or
  // e.Cell.Attributes.Add("class", "Invisible");
  // or
  // e.Cell.Attributes.Add("style", "display: none");
}

答案 3 :(得分:0)

如果你可以使用jQuery解决方案,只需几行代码:

<script type="text/javascript">
    $(document).ready(function () {
        $('._title').parent().attr('colspan', '5'); // title row initially has a colspan of seven
        $('._dayheader:first, ._dayheader:last', $('#<%= Calendar1.ClientID %>')).hide(); // remove first and last cells from day header row
        $('._weekendday').hide(); // remove all the cells marked weekends
    });
</script>

<asp:Calendar runat="server" ID="Calendar1">
    <TitleStyle CssClass="_title" />
    <DayHeaderStyle CssClass="_dayheader" />
    <WeekendDayStyle CssClass="_weekendday" />
</asp:Calendar>

以下是这种方法的一些注意事项:

  • 如果禁用JavaScript,客户端将会看到周末。
  • 在较旧的较慢浏览器中,jQuery在加载时执行跳转的日历类型。
  • 此解决方案可以使用:first-child直接在CSS中实现。
  • 如果您向页面添加其他日历,则需要复制JavaScript的中间行。这是必要的,因为我们正在使用:first和:last。
  • 如果页面上只有一个日历控件,则可以通过删除jQuery选择器的第二个参数来简化JavaScript的中间行:$('#<%= Calendar1.ClientID %>')

答案 4 :(得分:0)

正如zacharydl建议我设法使用jQuery隐藏周末。我对原始代码做了一些小改动。

 <script type="text/javascript">
   HideWeekEnd();


    function HideWeekEnd ()
    {
        $('._title').parent().attr('colspan', '7');  
        $('._dayheader:nth-last-child(1) , ._dayheader:nth-last-child(2) ', $('#<%= Calendar1.ClientID %>')).hide(); // remove last two cells from day header row
        $('._weekendday').hide(); // remove all the cells marked weekends
    }

 Sys.Application.add_init(appl_init);

        function appl_init() {
            var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
            pgRegMgr.add_endRequest(HideWeekEnd);
        }

</script>

您必须在页面endRequest中注册HideWeekEnd()以确保在页面回发期间调用它。

答案 5 :(得分:0)

这是另一种使用CSS来实现的方法:

 <style>
   .hidden,
   #Calendrier tr > th[abbr=Saturday],
   #Calendrier tr > th[abbr=Sunday] { display:none; }
   #Calendrier tr > th { text-align: center; }
 </style>

 <asp:Calendar ID="Calendar1" DayNameFormat="Full" runat="server" 
               WeekendDayStyle-CssClass="hidden" ClientIDMode="Static"  >
 </asp:Calendar>