Ja va Ja va - 1 month ago 11
C# Question

Change Calendar Date using interface after setting the date Programatically / C#/ASP.NET

How does a website user change the date of a calendar that has had its datetime set programatically(see code below)?

When a user goes a few months ahead or behind and tries to change the date on the calendar it just shoots back to the datetime that it was set.

Is there a way to resolve this dilemma?

In my example we have two calendars, one with the current datetime and another that is set 1 year ahead.

DateTime StartInputDate can be any date.

Basic Calendar Code / ASPX Page

<asp:Calendar ClientIDMode="Static" SelectionMode="Day" ID="clStartDate" Height="180px" Width="230px" runat="server"><SelectedDayStyle Font-Size="medium" /></asp:Calendar>

<asp:Calendar ClientIDMode="Static" ID="clMaintEndDate" Height="180px" Width="230px" runat="server"></asp:Calendar>


Setting Calendar to specific dates on Load/ ASPX.CS Page

clStartDate.SelectedDate = StartInputDate;
clStartDate.VisibleDate = StartInputDate;
clMaintEndDate.SelectedDate = StartInputDate.AddYears(1);
clMaintEndDate.VisibleDate = StartInputDate.AddYears(1);

Answer

Well, without seeing the code for your load method it's hard to say for sure, but I'm going to make some assumptions.

First, I'm assuming that you've got that calendar setting code in the Page_Load method. Is that true? If so, it could be that your calendars or something else on your page is causing a postback to the server and the calendars are getting reset to their initial values.

If that assumption is correct, to prevent the reset from happening, you typically will put the init (or initial setup) code behind an if block which checks to see if the page is posting back to the server. This is necessary because, in the page lifecycle, the Page_Load method is running every time the page is rendered, whether that's the first time or after a postback. So you'll typically see something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        //Your init code goes here...
        clStartDate.SelectedDate = StartInputDate;
        clStartDate.VisibleDate = StartInputDate;
        clMaintEndDate.SelectedDate = StartInputDate.AddYears(1);
        clMaintEndDate.VisibleDate = StartInputDate.AddYears(1);
    }
    //Other code which should run for every page_load goes here...
}

The second assumption is that you might be new to ASP.NET development. If so, this link explaining the page lifecycle will be really helpful.

If any of these assumptions are incorrect, update your post or comment on my answer to clarify as necessary and I'll be happy to update my answer.