将字符串数组绑定到DropDownList?

时间:2011-12-07 09:11:19

标签: c# asp.net visual-studio-2010

我从未解决过的问题。我将用两个代码示例进行说明,其中一个工作,另一个不工作:

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>

第一个DropDownList填充没有任何错误,因为每个对象oFamilyFontList都有一个属性'Name',它与DataText和DataValue字段绑定。

第二个没有任何属性,它只是一个字符串数组。我可以在两个字段中放置什么来使它工作?

1 个答案:

答案 0 :(得分:6)

是的,您可以绑定数组,但必须删除DataTextFieldDataValueField属性

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