DropDownList causes error: Object reference not set to an instance of an object

asp.net c# drop-down-menu entity-framework visual-studio-2010

Question

I keep getting this error and have no idea why. I googled and scanned the asp.net site for two days now so I need some help. The error is:

Object reference not set to an instance of an object

Here's my code:

DropDownList DropDownList1 =(DropDownList)ListView1.InsertItem.FindControl("DropDownList1");

string highToLow = DropDownList1.SelectedValue;
string lowToHigh = DropDownList1.SelectedValue;

if (highToLow == "1")
{
    var exmapleFilter = from users in testEntities.users 
                        orderby users.id descending
                        select users;

    ListView1.DataBind();
}

I have the value of the drop down set to 1 for high and 2 for low, and on selected index changed I want to run the ADO.net Entity Framework code to return a sorted list of data.

I'm currently using a linq data source and a list view to show what's in my database.

Thanks.

EDIT:

Here is the stack trace

   System.NullReferenceException was unhandled by user code
   Message=Object reference not set to an instance of an object.
   Source=App_Web_s0ked5y3

   StackTrace:
   at Default.DropDownList1_SelectedIndexChanged(Object sender, EventArgs e)
   in Default:line 120

   at System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e)

   at System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent()

   at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.
   RaisePostDataChangedEvent()

   at System.Web.UI.Page.RaiseChangedEvents()

   at System.Web.UI.Page.ProcessRequestMain(Boolean 
   includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   InnerException: 
1
3
7/5/2012 8:20:15 PM

Accepted Answer

Check that you have in your list view

<InsertItemTemplate>
   ....          
   <asp:DropDownList ID="DropDownList1" runat="server" />
   .... 

In association with

ListView1.InsertItem.FindControl("DropDownList1");
3
7/31/2012 8:35:08 AM

Popular Answer

"Object reference not set to an instance of an object" exception generally occurs when your are trying to use the reference variable whose value is null. It means that there is not corresponding object on heap.

So please make sure to double check your template and load all values in pageload event.

Hope it helps.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow