ERROR WHILE GETTING SELECTEDDATE FROM ASP:CALENDAR, OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJECT

Elena Glibart

Total Post:42

Points:296
Posted by  Elena Glibart
C#  OOPS 
 1051  View(s)
Ratings:
Rate this:

I have an <asp:Calendar> in my code and I want to do is that when a date is clicked, it will show the selected date on the page.

 

 protected void Calendar1_SelectionChanged(object sender, EventArgs e)

{

    Label1.Text = "The selected date is " + Calendar1.SelectedDate.ToShortDateString();

}

I followed the code instructions from here, Microsoft's website.

But I get this error.

System.NullReferenceException: Object reference not set to an instance of an object.

  1. lois waisbrooker

    Post:70

    Points:494
    Re: Error while getting SelectedDate from ASP:Calendar, Object reference not set to an instance of an object

    The reason is you have your Label1 inside the ContentPlaceHolder. When your .aspx child page uses that placeholder, the label is removed from masterpage. So in the SelectionChanged event it doesn't find your Label1.

     

    Move your Label outside of the mainContent ContentPlaceHolder

  1. Samuel Fernandes

    Post:159

    Points:1117
    Re: Error while getting SelectedDate from ASP:Calendar, Object reference not set to an instance of an object

    I copied the same code as you pasted and its working for me. I am getting the date properly on Selection_Changed event. protected void Calendar1_SelectionChanged(object sender, EventArgs e) { string tst = Calendar1.SelectedDate.ToShortDateString(); }

     

    the error you have mentioned can occur if your asp:Calendar control is in UpdatePanel.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!