【问题标题】:Why is this DropDownList data binding to a List<String> not working?为什么这个 DropDownList 数据绑定到 List<String> 不起作用?
【发布时间】:2011-04-28 22:20:13
【问题描述】:

我正在尝试将List&lt;String&gt; 绑定到用户控件中的DropDownList。我认为我在做正确的事,但似乎在我的代码执行后绑定被清除。这是供审查的代码!

用户控制:

<asp:DropDownList ID="subjectNameDropDown" runat="server"/>
<asp:DropDownList ID="yearLevelDropDown" runat="server"/>

自动生成的设计代码隐藏:

public partial class NewSiteMetadataUserControl {
    protected global::System.Web.UI.WebControls.DropDownList subjectNameDropDown;
    protected global::System.Web.UI.WebControls.DropDownList yearLevelDropDown;
}

代码隐藏:

public partial class NewSiteMetadataUserControl : UserControl
{
    protected override void CreateChildControls()
    {
        subjectNameDropDown = new DropDownList();
        yearLevelDropDown = new DropDownList();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        EnsureChildControls();

        // Attempt 1
        List<String> subjectNames = GetSubjectValues();
        foreach (var subjectName in subjectNames)
            subjectNameDropDown.Items.Add(subjectName);
        subjectNameDropDown.DataBind();

        // Attempt 2
        List<String> yearLevels = GetYearLevelValues();
        yearLevelDropDown.DataSource = yearLevels;
        yearLevelDropDown.DataBind();
    }
}

这种方法应该管用吗?

如果应该,如何调试代码执行后发生的情况?

【问题讨论】:

    标签: asp.net data-binding user-controls drop-down-menu


    【解决方案1】:

    是的,这种方法应该可行,这就是为什么目前不行,

    • 使用DataBind 完成的下拉列表需要DataSource。这就是尝试 #1 不起作用的原因。
    • 如果您绑定到List&lt;string&gt;,则没有明确的键/值对可以绑定。这就是为什么在绑定到List&lt;Person&gt;(例如)时,需要在Person 类中重写.ToString() 以提供键/值绑定,或者手动设置DataTextFieldDataValueField。李>
    • ASP.NET 无法为string 计算出键/值对。

    想想你想要的HTML。简单字符串的键/值应该是什么?这样做没有意义。

    由于您并不真正关心“键”(只关心显示的内容),我建议您改为绑定到 Dictionary&lt;TKey,TValue&gt;

    要么让你的方法返回它,要么遍历列表并将它们添加到带有索引的字典中。

    【讨论】:

      【解决方案2】:

      这里的问题是CreateChildControls。在我尝试完成这项工作的某个地方,我添加了这个初始化控件的方法。这不是必需的,实际上导致数据绑定被清除,因为它是在OnLoad 之后由框架自动调用的。

      解决方案是删除此方法和对EnsureChildControls 的调用。

      【讨论】:

        猜你喜欢
        • 2010-10-26
        • 2014-05-31
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        相关资源
        最近更新 更多