Hatem
Hatem

Reputation: 589

SelectedDate not working for Calendar object

Am trying to set a new date for Calendar object on ASP.NET , but nothing changed. Here is my code :

protected void Page_Load(object sender, EventArgs e)
{

    if (Page.IsPostBack)
    {
        cld_birth.SelectedDate = new DateTime(2003, 1, 1);
    }
}

Upvotes: 3

Views: 7024

Answers (5)

B H
B H

Reputation: 1878

Do as @Martin-Brennan suggests, but the code may need to be placed in the Page_PreRender event handler.

  protected void Page_PreRender(object sender, EventArgs e)
  {
    if (Page.IsPostBack)
    {
      cld_birth.SelectedDate = new DateTime(2003, 1, 1);
      cld_birth.VisibleDate = new DateTime(2003, 1, 1);
    }
  }

Upvotes: 0

walbury
walbury

Reputation: 78

There is an additional issue where the selected date is not highlighted (ie SelectedDayStyle is ignored) if the date contains a non-midnight time. You'd expect the first option to be ok. No, unfortunately

            Dim oDt As New Date()
            oDt = Now                
            Dim oDtYesterday As New Date
            oDtYesterday = DateAdd(DateInterval.Day, -1, oDt)

            'oDtYesterday is all fine, but does not highlight
            'calDateFrom.SelectedDate = oDtYesterday 

            Dim sDateYesterday As String
            sDateYesterday = Format(oDtYesterday, "dd MMM yyyy")

            Dim oDtY As New Date
            oDtY = CDate(sDateYesterday & " 12:00:00 AM")

            calDateFrom.SelectedDate = oDtY 
            calDateFrom.VisibleDate = calDateFrom.SelectedDate

Upvotes: 3

4b0
4b0

Reputation: 22323

You must define SelectedDayStyle in your control.

<asp:Calendar ID="cld_birth" runat="server">
   <SelectedDayStyle Font-Size="X-Large" />
</asp:Calendar>

And use:

if (!Page.IsPostBack)
{
  cld_birth.SelectedDate = new DateTime(2003, 1, 1);
}

Upvotes: 1

Martin-Brennan
Martin-Brennan

Reputation: 927

Try setting the VisibleDate as well:

if (Page.IsPostBack)
{
    cld_birth.SelectedDate = new DateTime(2003, 1, 1);
    cld_birth.VisibleDate = new DateTime(2003, 1, 1);
}

Upvotes: 9

Priyank Patel
Priyank Patel

Reputation: 6996

If you want to set the time when the page is loaded for the first time then use IsPostBack Property to determine if the page is loaded for the first time or if the page is Posted back.

if (!Page.IsPostBack)
    {
        cld_birth.SelectedDate = new DateTime(2003, 1, 1);
    }

Upvotes: 1

Related Questions