Ajax CalendarExtender, How to get the date after i click on a button?

Youssef picture Youssef · Sep 22, 2011 · Viewed 12.9k times · Source

I want to add add an Ajax CalendarExtender to my page. And then after selecting a date and clicking on a button I get the selected Day in a label.

I have a text box which is the target of the CalendarExtender

<asp:TextBox ID="DateText" runat="server" ReadOnly="true" ></asp:TextBox>

<ajaxToolkit:CalendarExtender 
    ID="Calendar1"
    runat="server"
    TargetControlID="DateText"
    Format="MMMM d, yyyy"
    PopupPosition="Right"
    />

<asp:Button runat="server" ID="Button1" onclick="Button1_Click" />

In the Code Behind:

On the first page load I set the date to Today.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Calendar1.SelectedDate = DateTime.Today;
    }
}

In the Button1_Click Event

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = Calendar1.SelectedDate.Value.Day.ToString();
}

The problem is when I click the button (or after any post backs) the value selected get reset to Today's date.

And if I don't set it to DateTime.Today in the Page_Load It get reset to null and throw a null exception.

How can I solve this?

Thank you very much for any help. I hope i was clear

Answer

Hanlet Esca&#241;o picture Hanlet Escaño · Sep 22, 2011

Maybe this will work:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if(!Calendar1.SelectedDate)
            Calendar1.SelectedDate = DateTime.Today;
    }
}