【问题标题】:How to bind dictionary with containing list to grid view如何将包含列表的字典绑定到网格视图
【发布时间】:2014-01-11 22:23:54
【问题描述】:

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

   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#

【问题讨论】:

  • 你也可以标记编程语言吗?
  • 它在绑定的网格视图中显示一些通用类名

标签: c# asp.net gridview dictionary


【解决方案1】:

您需要将 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>

它的显示方式如下:

你可以下载我用来测试你的代码的测试项目here

【讨论】:

  • 但是在上面的代码中,电影列表值没有打印出来,而不是打印下面提到的值——System.Collections.Generic.List`1[System.String] 请为此提供解决方案列表中的所有内容也绑定在网格视图中
  • @Shiv 这将取决于您希望如何显示这些值。您可以在网格中为 Movies 列创建一个 TemplateField,并在其 ItemTemplate 中放置一个 Listbox,将 DataSource 设置为模型的 .Movies 属性。例如像 &lt;asp:ListBox runat="server" Datasource='&lt;%# Eval("Movies") %&gt;' /&gt; 这样的东西应该可以正常工作。
  • @Shiv 另外,我认为图像 url 对你来说可能没用?在这种情况下,您可以使用 ImageField 并将其 DataImageUrlField 属性设置为“照片”,如下所示:&lt;asp:ImageField runat="server" DataImageUrlField="Photo" /&gt;。请记住,afzalulh 可能使用了 Grid 上的 AutogenerateColumns 属性来创建基本布局。如果您的模型不只包含简单的字段,例如整数和字符串,您可能需要构建自己的列或使用更灵活的东西,例如 Dynamic Data
  • @julealgon - 即使在 OP 指向它之后,我也没有注意到有电影列表!可怜的我:-(
  • thanx 很多...代码工作得非常好....在我使用标签之前,这就是为什么它不起作用但在使用之后 -- 成功了……再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 2011-01-01
相关资源
最近更新 更多