AJAX store data between postbacks (calendars)

Rating: 193 user(s) have rated this article Average rating: 4.9
Posted by: sergey, on 19/08/2008, in category "ASP.NET"
Views: this article has been read 15061 times
Location: United Kingdom
Abstract: In this article I will explain how we can save selected by user data in calendar controls. This will be useful when you generate some "ad hoc" report in your web application.

 Very often we use in our reports date controls (like calendar) where our users can select required interval of dates for their reports. After interval has been chosen we need regenerate our web page and display some information. The problem we are challenged in ASP.NET environment is - how to preserve user's choice between post backs?

Personally, I would prefer to have things as simple as possible. For preserving data we will use standard control as a TextBox. So, for the one of the date we will have the next:
 
<asp:TextBox ID="txtDatStart" Width="85px" runat="server" OnTextChanged="txtDatStart_TextChanged" />
<asp:ImageButton runat="Server" ID="Image1" ImageUrl="~/images/Calendar_schedule.bmp" AlternateText="Please click button to show calendar" />
<ajaxToolkit:CalendarExtender ID="CalendarStart" runat="server" TargetControlID="txtDatStart" PopupButtonID="Image1" />
 
Method "txtDatStart_TextChanged" will be very simple:
 
protected void txtDatEnd_TextChanged(object sender, EventArgs e)
{
 CalendarEnd.SelectedDate = Convert.ToDateTime(txtDatEnd.Text);
}
 
And finally we must modify the Page_Load method:
 
protected void Page_Load(object sender, EventArgs e)
{
 if (IsPostBack)
   {
      if (!string.IsNullOrEmpty(txtDatStart.Text))
      {
        CalendarStart.SelectedDate = Convert.ToDateTime(this.txtDatStart.Text);
        CalendarEnd.SelectedDate = Convert.ToDateTime(this.txtDatEnd.Text);
      }
    }
     else
    {
       CalendarStart.SelectedDate = DateTime.Today;
       CalendarEnd.SelectedDate = DateTime.Today;
    }
}
 
In this method were shown actually two controls for the start and end dates.
Good luck!

How would you rate this article?

User Feedback

Post your comment:
Name:
E-mail:
Comment:
Insert Cancel