简体   繁体   中英

How to bind dictionary with containing list to grid view

How to bind this dictionary to grid view -

   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)"}
        }
    }, 
};

using c# in asp.net

You need to set GridView DataDource to Dictionary.Values like below:

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

EDIT : And the markup may look like this (thanks julealgon for pointing to Movies List) :

<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>

Here's how it is displayed: 在此处输入图片说明

You can download the test project I have used to test your code here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM