Partager via


How to: Set Today's Date Programmatically in a Calendar Web Server Control

By default, the value of "today" in the Calendar control is set to match the date of the server on which the Web Forms page runs. However, you might need to adjust the date to accommodate users who are viewing the page from a different time zone.

To set today's date programmatically

  • Set the Calendar control's TodaysDate property to a DateTime value.

    The following example sets TodaysDate to tomorrow and then sets the SelectedDate to TodaysDate. In the browser, the date for tomorrow will be highlighted.

    Dim tomorrow As Date = Date.Today.AddDays(1)
    Calendar1.TodaysDate = tomorrow
    Calendar1.SelectedDate = Calendar1.TodaysDate
    
    DateTime tomorrow = DateTime.Today.AddDays(1);
    Calendar1.TodaysDate = tomorrow;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
    

    The following example shows how you can fill a DropDownList control with a selection of dates and then set the value of today's date in the Calendar control according to the user's selection from the list.

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim today As DateTime = System.DateTime.Today
            Dim yesterday As DateTime = today.AddDays(-1)
            Dim tomorrow As DateTime = today.AddDays(1)
            DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
               today))
            DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
               yesterday))
            DropDownList1.items.Add(String.Format("{0:dd MMM yyyy}", _
               tomorrow))
        End If
    End Sub
    
    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender _
            As Object, ByVal e As System.EventArgs) _
            Handles DropDownList1.SelectedIndexChanged
        Calendar1.TodaysDate = _
            Date.Parse(DropDownList1.SelectedItem.Text)
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DateTime today = System.DateTime.Today;
            DateTime yesterday = today.AddDays(-1);
            DateTime tomorrow = today.AddDays(1);
            DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}",
               today));
            DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}",
               yesterday));
            DropDownList1.Items.Add(String.Format("{0:dd MMM yyyy}",
               tomorrow));
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, 
        EventArgs e)
    {
        Calendar1.TodaysDate = 
            DateTime.Parse(DropDownList1.SelectedItem.Text);
    }
    

See Also

Concepts

Calendar Web Server Control Overview