Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding array of string to DropDownList?

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 ?

like image 309
yahya kh Avatar asked Dec 07 '11 09:12

yahya kh


1 Answers

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

<asp:DropDownList 
        ID="DropDownList_FontColor"
        runat="server">
</asp:DropDownList>
like image 149
KV Prajapati Avatar answered Oct 15 '22 05:10

KV Prajapati