如何将包含列表的字典绑定到网格视图

时间:2013-12-23 17:07:18

标签: c# asp.net gridview dictionary

如何将此词典绑定到网格视图 -

   Dictionary<int, Actor> actors = new Dictionary<int, Actor>{
    {
        1,new Actor
        {
            ActorId = 1,
            ActorName= "Rajanikant",
            BirthDate =DateTime.Parse("12-12-1949"), 
            BirthPlace ="Bangalore", 
            Photo ="~/Images/1.jpg", 
            Movies = new List<string>{"Shivaji (2007)","Baba (2002)","ChaalBaaz (1989)"}
        }
    },                 
    {
        2,new Actor
        {
            ActorId = 2,
            ActorName= "Jennifer Aniston", 
            BirthDate =DateTime.Parse("11-2-1969"), 
            BirthPlace ="Sherman Oaks", 
            Photo ="~/Images/2.jpg", 
            Movies=new List<string>{"Friends (1994)","Bruce Almighty (2003)","Just Go with It (2011)"}
        }
    }, 
};

在asp.net中使用c#

1 个答案:

答案 0 :(得分:4)

您需要将GridView DataDource设置为 Dictionary.Values ,如下所示:

GridView1.DataSource = actors.Values;
GridView1.DataBind();

编辑:标记可能如下所示(感谢julealgon指向电影列表):

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
    <Columns>
        <asp:BoundField DataField="ActorId" HeaderText="Actor Id" />
        <asp:BoundField DataField="ActorName" HeaderText="Actor Name"  />
        <asp:BoundField DataField="BirthDate" HeaderText="Birth Date"  />
        <asp:BoundField DataField="BirthPlace" HeaderText="Birth Place"  />   
        <asp:TemplateField  HeaderText="Photo" >
            <ItemTemplate>
                <asp:Image ID="Image1" ImageUrl='<%#Eval("Photo") %>'  runat="server" />
                </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Movies" >
            <ItemTemplate>
                <asp:ListBox ID="ListBox1" DataSource='<%#Eval("Movies") %>' runat="server"></asp:ListBox>
                </ItemTemplate>
        </asp:TemplateField>   
    </Columns>
</asp:GridView>

以下是它的显示方式: enter image description here

您可以下载我用于测试代码的测试项目here