自定义日历控件中的选择

时间:2012-08-09 04:03:03

标签: c# asp.net calendar

我在Asp.Net中使用日历控件。我想要实现的条件是"如果用户从一周选择特定的工作日,他应该不能从任何不同的周选择任何其他日期"。比如,所有选择应该只在一周内完成。但我无法弄清楚除了选定日期的一周之外如何禁用剩下的几周。

1 个答案:

答案 0 :(得分:0)

我会这样做...当所选日期改变时,获取该特定周的开始和结束。然后,当每天渲染时,确保该日落在该周范围内。

private DateTime? _firstDayOfWeek;
private DateTime? _lastDayOfWeek;

protected void yourCalendar_SelectionChanged(object sender, EventArgs e)
{
    var selectedDate = yourCalendar.SelectedDate;

    DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

    _firstDayOfWeek = selectedDate.Date;
    while (_firstDayOfWeek.Value.DayOfWeek != firstDay)
        _firstDayOfWeek = _firstDayOfWeek.Value.AddDays(-1);

    _lastDayOfWeek = selectedDate.Date;
    while (_lastDayOfWeek.Value.DayOfWeek != _firstDayOfWeek.Value.AddDays(6).DayOfWeek)
        _lastDayOfWeek = _lastDayOfWeek.Value.AddDays(1);
}

protected void yourCalendar_DayRender(object sender, DayRenderEventArgs e)
{
    if (_firstDayOfWeek.HasValue && _lastDayOfWeek.HasValue)
    {
        // There are dates to work with now, so check to see if the day falls
        // outside of the week range...
        if (e.Day.Date.Ticks < _firstDayOfWeek.Value.Ticks || e.Day.Date.Ticks > _lastDayOfWeek.Value.Ticks)
            e.Day.IsSelectable = false;
    }
}