日历控件 - 程序化地突出显示日期

4

我正在尝试使用日历控件,但似乎无法完成简单的日期标记任务。如果用户输入了7个日期,我希望在日历上标记这些日期,以便用户知道它们已被选择。

本质上,我想要实现 Calendar.HighlightDate("5/1/11") => 虚构的lol。我知道这一定很简单,但我正在浏览MSDN上的属性,却没有找到任何信息。

2个回答

6

设置日历对象的ondayrender事件:

<asp:Calendar ID="Calendar1" runat="server" ondayrender="MyDayRenderer">

然后在你的代码中,你可以检查日期并设置颜色:
   protected void MyDayRenderer(object sender, DayRenderEventArgs e)
    {
        if (e.Day.IsToday)
        {
            e.Cell.BackColor = System.Drawing.Color.Aqua;
        }

        if (e.Day.Date == new DateTime(2011,5,1))
        {
            e.Cell.BackColor = System.Drawing.Color.Beige;
        }
    }

对不起,John。我登录后只看到了第一个答案,这周我很忙。 - bumble_bee_tuna

2

这是我很久以前在一个项目中使用的一些代码。现在可能有更好的方法,但这应该可以工作。我能找到的最简单的方法是进入DayRender事件。

我用这个来突出显示某些已预订、待定或可租赁物业的日期。

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    for (int x = 0; x < ar.Count; x++)
    {
        //if the date is in the past, just mark it as booked.
        if (e.Day.Date < DateTime.Now)
        {
            e.Cell.BackColor = System.Drawing.Color.FromArgb(38, 127, 0);
            e.Cell.ForeColor = System.Drawing.Color.White;
        }

        if (e.Day.Date.ToShortDateString() == Convert.ToDateTime(((ListItem)ar[x]).Text).ToShortDateString())
        {
            switch (((ListItem)ar[x]).Value)
            { 
                case "1":
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(220,220,220);
                    break;
                case "2":
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(38,127,0);
                    e.Cell.ForeColor = System.Drawing.Color.White;
                    break;
                case "3":
                    if (e.Day.IsWeekend)
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(255,255,204);
                    }
                    else
                    {
                        e.Cell.BackColor = System.Drawing.Color.White;
                    }
                    break;
                default:
                    e.Cell.BackColor = System.Drawing.Color.White;
                    break;
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接