【问题标题】:How to bind a generic list of enums to a GridView如何将通用枚举列表绑定到 GridView
【发布时间】:2016-02-11 23:11:31
【问题描述】:

我无法将通用枚举列表绑定到 GridView,以下是所有详细信息:

错误信息

ID 为“GridView1”的 GridView 的数据源没有任何属性或属性可用于生成列。确保您的数据源有内容。

ASPX 页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Amikids.Pages.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

代码背后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Amikids.Pages
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public enum Pet
        {
            Cat = 0,
            Dog = 1,
            Bird = 2
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Pet> pets = new List<Pet>();
            pets.Add(Pet.Bird);
            pets.Add(Pet.Dog);

            GridView1.DataSource = pets;
            GridView1.DataBind();
        }
    }
}

【问题讨论】:

  • @DavidTansey - 在您提供的帖子中,它们绑定到一个对象,该对象包含一个类型为枚举的属性。我绑定到枚举值列表。重要的区别是没有要使用的数据字段名称。起初,您似乎可以使用枚举名称作为数据字段名称。但是,就像您绑定到字符串列表(即 List)一样,您不能使用单词“string”作为数据字段名称。希望这是有道理的。

标签: asp.net list generics gridview enums


【解决方案1】:

我无法弄清楚如何将枚举值列表直接绑定到 GridView。作为解决方法,我将枚举值列表转换为字符串值列表。

以下 - 将枚举值列表转换为字符串值列表的代码。

public static List<string> ConvertListOfPetsToListOfStrings(List<Pet> pets)
{
    List<string> listOfStrings = new List<string>();
    foreach (Pet pet in pets)
    {
        listOfStrings.Add(pet.ToString());
    }
    return listOfStrings;
}

以下 - 绑定到 GridView 的代码

        GridView1.DataSource = ConvertListOfPetsToListOfStrings(pets);
        GridView1.DataBind();

以下 - 用于绑定到模板字段并设置有意义的 HeaderText 的 ASPX 标记。

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:TemplateField HeaderText="Type of Pet">
                <ItemTemplate>
                    <%# Container.DataItem %>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

【讨论】:

    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多