I’m developing a calendar for ASP.NET. I’m not using the Calendar control because it’s quite limited.
I was wondering how can I programmatically switch between different months, for example, show a previous and a next month?
Now I get to change a month only once and then the month gets stuck: if July is shown first, then I can only get to June. When I’m on June and push the next month button, it shows me August. Would AJAX be a good choice to solve this problem?
My code:
private static DateTime now = DateTime.Today;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrev_Click(object sender, EventArgs e)
{
lblDateCal.Text = now.AddMonths(-1).ToString("MMMM");
}
protected void btnNext_Click(object sender, EventArgs e)
{
lblDateCal.Text = now.AddMonths(+1).ToString("MMMM");
}
Each time, you are using Now() to increment or decrement the month by one. You need to save your current month you are navigating to. E.g., save the last date you navigated to in the ViewState, and use that in your click events instead of Now().
for example:
otherwise, if you prefer to use a static variable, then you need to utilize your static variable properly, by setting it each click. That is to say, the AddMonths() method does not implicitly modify your variable.
e.g.
However, since static variables are global to the application, I would not think is the best approach.
Here is a good thread on that here: static variables in asp.net/C#