How to: Select Dates Programmatically in a Calendar Web Server Control

You can set date selections in your own code, either a single date or a range of dates. In contrast to user selection in the control on a page, you can select multiple non-sequential dates in code.

Note Note

Setting a date programmatically does not raise the SelectionChanged event.

To select a single date

  • Set the control's SelectedDate property to an expression of type DateTime.

    Calendar1.SelectedDate = DateTime.Today;

    If you set the SelectedDate, all the dates in SelectedDates are effectively cleared.

To select a range of dates

  • Call the Add method of the control's SelectedDates collection. You can add dates in any order, because the collection will order them for you. The collection also enforces uniqueness and will therefore ignore a date you add if the date is already in the collection.

    The following example sets the selection to every Wednesday in the month of February, 2000.

    public void Button1_Click (object sender, System.EventArgs e)
       SelectedDatesCollection theDates = Calendar1.SelectedDates;
       theDates.Add(new DateTime(2000,2,2));
       theDates.Add(new DateTime(2000,2,9));
       theDates.Add(new DateTime(2000,2,16));
       theDates.Add(new DateTime(2000,2,23));

    The following example selects a sequence of seven dates.

    DateTime aDate = DateTime.Today;
    SelectedDatesCollection theDates = Calendar1.SelectedDates;
    for (int i = 0;i <= 6;i++)

To clear a date selection

  • Call the Clear method of the control's SelectedDates collection, as in the following example: