DropDownList导致错误:对象引用未设置为对象的实例

时间:2012-07-05 20:00:45

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

我一直收到这个错误并且不知道为什么。我用谷歌搜索并扫描了asp.net网站两天,所以我需要一些帮助。错误是:

Object reference not set to an instance of an object

这是我的代码:

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();
}

我将下拉列表的值设置为1表示高,2表示低,并且选中的索引已更改我想运行ADO.net Entity Framework代码以返回已排序的数据列表。

我目前正在使用linq数据源和列表视图来显示我的数据库中的内容。

感谢。

编辑:

这是堆栈跟踪

   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: 

3 个答案:

答案 0 :(得分:3)

检查列表视图中是否有

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

相关联
ListView1.InsertItem.FindControl("DropDownList1");

答案 1 :(得分:0)

基于他们的无堆栈跟踪,我的疑问是这条线:

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

导致oObject引用未设置为对象的实例

一个强有力的原因:名为InsertItem的控件不是ListView1的子控件

答案 2 :(得分:0)

“对象引用未设置为对象的实例”异常通常在您尝试使用其值为null的引用变量时发生。这意味着堆上没有相应的对象。

因此,请务必仔细检查您的模板并加载pageload事件中的所有值。

希望它有所帮助。

相关问题