简体   繁体   中英

Select dates in asp.net Calendar programatically

I'm using Calendar controller in my asp.net web forms application. I followed this article to implement Calendar in my application. I'm adding selected days into a List<DateTime> to remember selected dates and use them in future actions.

Now I have added buttons to my page like Select Weekends , Select Weekdays , Select Month and Select Year .

  • if I click on the Select Weekends button, I need to select all weekend days of current month and add them into List<DateTime> .

  • if I click on the Select Weekdays button, I need to select all week days of current month and add them into List<DateTime> .

  • if I click on the Select Month ** button, I need to select all days of the current month and add them into List<DateTime> .

  • if I click on the Select Year button, I need to select all days of the current year and add them into List<DateTime> .

How can I do this programatically using C#?

I don't think there's a miracle solution, here how I would write 2 methods to what you want for the weekend days. For the other points, you could do more or less the same thing:

    protected void WeekendDays_Button_Click(object sender, EventArgs e)
    {
        this.SelectWeekEnds():
    }

    private void SelectWeekEnds(){
        //If you need to get the selected date from calendar
        //DateTime dt = this.Calendar1.SelectedDate;

        //If you need to get the current date from today
        DateTime dt = DateTime.Now;

        List<DateTime> weekendDays = this.SelectedWeekEnds(dt);
        weekendDays.ForEach(d => this.Calendar1.SelectedDates.Add(d));
    }

    private List<DateTime> GetWeekEndDays(DateTime DT){
        List<DateTime> result = new List<DateTime>();
        int month = DT.Month;
        DT = DT.AddDays(-DT.Day+1);//Sets DT to first day of month

        //Sets DT to the first week-end day of the month;
        if(DT.DayOfWeek != DayOfWeek.Sunday)
            while (DT.DayOfWeek != DayOfWeek.Saturday)
                DT = DT.AddDays(1);

        //Adds the week-end day and stops when next month is reached.
        while (DT.Month == month)
        {
            result.Add(DT);
            DT = DT.AddDays(DT.DayOfWeek == DayOfWeek.Saturday ? 1 : 6);
        }
        return result;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM