无法将数据绑定到DropDownList - NullReferenceException

时间:2013-09-20 18:07:04

标签: c# .net data-binding drop-down-menu webforms

我正在尝试将数据绑定到我使用DropDownList标记创建的<asp:DropDownList。它成功地适用于第一个DropDownList,但其余两个抛出异常。我知道数据源是 null并且确实有值,所以我唯一能想到的是其他两个列表框尚未加载或绑定。

我尝试使用Page_LoadComplete方法添加内容,但似乎没有触发。我已经习惯了MVC而且我对Web Forms很新,所以我不确定我做错了什么。我是否正确说明元素尚未加载,如果是,如何在加载后绑定它们

protected void Page_Load(object sender, EventArgs e)
    {
        //Page.LoadComplete += new EventHandler(Page_LoadComplete);
        if (DataContext == null)
        {
            DataContext = new ReuseLibraryDataContext(SPContext.Current.Web.Url);
        }

        // top level category for all documents
        _functions = DataContext.ReuseLibrary.Select(p => p.FunctionalCategories).Distinct().ToList();

        // the first sub category
        _sc1 = DataContext.ReuseLibrary.Select(p => p.SubCategoriesLevel1).Distinct().ToList();

        // the second sub category
        _sc2 = DataContext.ReuseLibrary.Select(p => p.SubCategoriesLevel2).Distinct().ToList();


        // add the functions to the dropdown
        listFunctions.DataSource = _functions;
        listFunctions.DataBind();

        // add the sub cat 1 to the dropdown
        listSC1.DataSource = _sc1;
        listSC1.DataBind();

        // add the sub cat 2 to the dropdown
        listSC2.DataSource = _sc2;
        listSC2.DataBind();
    }

    //protected void Page_LoadComplete(object sender, EventArgs e)
    //{
    //    // add the functions to the dropdown
    //    listFunctions.DataSource = _functions;
    //    listFunctions.DataBind();

    //    // add the sub cat 1 to the dropdown
    //    listSC1.DataSource = _sc1;
    //    listSC1.DataBind();

    //    // add the sub cat 2 to the dropdown
    //    listSC2.DataSource = _sc2;
    //    listSC2.DataBind();
    //}

1 个答案:

答案 0 :(得分:3)

我觉得自己很愚蠢 - 但我会发布问题所在以防其他人被这样的事情抓住。

即使我提供了一个数据列表,该列表中的任何null个对象也会抛出NullReferenceException。很容易理解。

要解决我删除了null值和中提琴。按预期工作。

_sc1.RemoveAll(item => item == null);
_sc2.RemoveAll(item => item == null);

我最终更新了查询以排除空值:

_sc1 = DataContext.ReuseLibrary.Select(p => p.SubCategoriesLevel1).Where(p => p != null).Distinct().ToList();

相关问题