yahya kh
yahya kh

Reputation: 751

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 ?

Upvotes: 6

Views: 18433

Answers (1)

KV Prajapati
KV Prajapati

Reputation: 94653

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

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

Upvotes: 6

Related Questions