Binding array of string to DropDownList?

99封情书 提交于 2020-01-02 03:34:17

问题


A question that I have never solved. I will illustrate with two code samples in which one works and the other doesn't:

Page_Load()
{
        FontFamily[] oFamilyFontList = FontFamily.Families;
        DropDownList_Fonts.DataSource = oFamilyFontList;
        DropDownList_Fonts.DataBind();

        string[] colorName = System.Enum.GetNames(typeof(KnownColor));
        DropDownList_FontColor.DataSource = colorName;
        DropDownList_FontColor.DataBind();
}
    <asp:DropDownList 
        ID="DropDownList_Fonts" DataTextField="Name" 
        DataValueField="Name" runat="server" >
    </asp:DropDownList>

    <asp:DropDownList 
        ID="DropDownList_FontColor"  DataTextField="colorName" 
        DataValueField="colorName" runat="server" >
    </asp:DropDownList>

The first DropDownList populates fine without any errors because each object oFamilyFontList has a property 'Name' which binds with the DataText and DataValue fields.

The second one has no properties at all and it's just an array of strings. What possibly can I put inside both fields to make it work ?


回答1:


Yes you can bind an array but you have to remove DataTextField and DataValueField attributes

<asp:DropDownList 
        ID="DropDownList_FontColor"
        runat="server">
</asp:DropDownList>


来源:https://stackoverflow.com/questions/8412774/binding-array-of-string-to-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!