问题描述
我对Calendar控件有疑问。我不知道如何选择一年中星期六的第二周。我必须使用Calendar控件。它的前景应为红色。我应该使用bool标志来选择星期六的第二周吗?
I have got a doubt in Calendar control. I don't know how to select all the second week of Saturday in a year. I have to use Calendar control. Its forecolor should be in Red color. Should i use bool flag for selecting second week of Saturday?
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
bool flag = false;
if (e.Day.Date.DayOfWeek.ToString() == "Saturday")
{
flag = true;
e.Cell.ForeColor = System.Drawing.Color.Red;
}
if(!flag)
{
}
}
}
推荐答案
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
CalendarDay dateToCheck = e.Day;
if(Is2ndSaturday(dateToCheck.Date))
{
e.Cell.BackColor = Color.Red;
}
}
设置和检查 flag
这是毫无意义的但是如果你想加快速度,那么一旦你已经突出显示当年的日期,你就可以跳过测试。
函数 Is2ndSaturday
下面采取相当强力的方法。我从1月1日开始显示当年,检查是否(1月1日)已经是星期六,如果不是只是增加工作日期,直到它找到星期六。这将是第一个星期六,所以一旦你找到它,只需要加7天就可以找到第二个星期六。
这里我只是将第二个星期六的日期与输入日期和如果匹配则返回bool。您可以更改它以返回日期。
Setting and checking flag
is fairly pointless but if you wanted to speed things up you could skip the test each year once you've already highlighted the date for that year.
The function Is2ndSaturday
below takes a fairly "brute force" approach. I start with January 1st for the year being displayed, checks to see if it (1st Jan) is already a Saturday and if not just increment a working date until it finds a Saturday. That will be the first Saturday, so once you've found it, just add 7 days to find the second Saturday.
Here I've just compared the date of the second Saturday to the input date and return a bool if they match. You could change it to return the date instead.
private bool Is2ndSaturday(DateTime dtIn)
{
// get the first day of the year for the current date
DateTime dt1 = new DateTime(dtIn.Year, 1, 1);
//Check to see if it's a saturday
while (dt1.DayOfWeek != DayOfWeek.Saturday)
{
dt1.AddDays(1.0);
}
dt1.AddDays(7); //dt1 now contains the date of the 2nd saturday for this year
//Check to see if the day we are working on is that 2nd saturday
return (dtIn.CompareTo(dt1) == 0) ? true : false;
}
这篇关于如何在Asp.net c#中使用Calendar控件使星期六的所有星期六都变为红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!