Partager via


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

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 = Date.Today
    
    Calendar1.SelectedDate = DateTime.Today;
    

    Note

    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.

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    
       With Calendar1.SelectedDates
          .Clear()
          .Add(New Date(2000, 2, 2))
          .Add(New Date(2000, 2, 9))
          .Add(New Date(2000, 2, 16))
          .Add(New Date(2000, 2, 23))
       End With
    End Sub
    
    public void Button1_Click (object sender, System.EventArgs e)
    {
       SelectedDatesCollection theDates = Calendar1.SelectedDates;
       theDates.Clear();
       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.

    Dim today As Date = Date.Today
    Dim i As Integer
    
    With Calendar1.SelectedDates
       .Clear()
       For i = 0 To 6
          .Add(today.AddDays(i))
       Next
    End With
    
    DateTime aDate = DateTime.Today;
    SelectedDatesCollection theDates = Calendar1.SelectedDates;
    theDates.Clear();
    for (int i = 0;i <= 6;i++)
    {
          theDates.Add(aDate.AddDays(i));
    }
    

To clear a date selection

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

    Calendar1.SelectedDates.Clear()
    
    Calendar1.SelectedDates.Clear();
    

See Also

Concepts

Calendar Web Server Control Overview