当前位置:编程学习 > 网站相关 >>

Repeater绑定dictionary数据源

 

.aspx页面代码


 

[html]
asp:Repeater ID="Repeater1" runat="server"> 
    <ItemTemplate> 
        <%#  ((KeyValuePair<int, List<User>>)Container.DataItem).Key %> <br /> 
        <asp:Repeater ID="Repeater2" runat="server" DataSource='<%#  ((KeyValuePair<int, List<User>>)Container.DataItem).Value %>'> 
            <ItemTemplate> 
                <%# (Container.DataItem as User).Id %> 
                <%# (Container.DataItem as User).Name %> 
            </ItemTemplate> 
        </asp:Repeater> 
        <hr /> 
    </ItemTemplate> 
</asp:Repeater> 

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <%#  ((KeyValuePair<int, List<User>>)Container.DataItem).Key %> <br />
            <asp:Repeater ID="Repeater2" runat="server" DataSource='<%#  ((KeyValuePair<int, List<User>>)Container.DataItem).Value %>'>
                <ItemTemplate>
                    <%# (Container.DataItem as User).Id %>
                    <%# (Container.DataItem as User).Name %>
                </ItemTemplate>
            </asp:Repeater>
            <hr />
        </ItemTemplate>
    </asp:Repeater>
 

 

.aspx.cs后置代码


[csharp]
public partial class Temp : System.Web.UI.Page 

    Dictionary<int, List<User>> dict = new Dictionary<int, List<User>>(); 
 
    protected void Page_Load(object sender, EventArgs e) 
    { 
        dict.Add(1, new List<User> 
        { 
            new User{Id = 1, Name = "aa"} 
            ,new User{Id = 2, Name = "bb"} 
        }); 
 
        dict.Add(2, new List<User> 
        { 
            new User{Id = 3, Name = "cc"} 
            ,new User{Id = 4, Name = "dd"} 
        }); 
 
        Repeater1.DataSource = dict; 
        Repeater1.DataBind(); 
    }  

 
public class User 

    public int Id{get;set;} 
    public string Name{get;set;} 

public partial class Temp : System.Web.UI.Page
{
    Dictionary<int, List<User>> dict = new Dictionary<int, List<User>>();

    protected void Page_Load(object sender, EventArgs e)
    {
        dict.Add(1, new List<User>
        {
            new User{Id = 1, Name = "aa"}
            ,new User{Id = 2, Name = "bb"}
        });

        dict.Add(2, new List<User>
        {
            new User{Id = 3, Name = "cc"}
            ,new User{Id = 4, Name = "dd"}
        });

        Repeater1.DataSource = dict;
        Repeater1.DataBind();
    }
}

public class User
{
    public int Id{get;set;}
    public string Name{get;set;}
}

 

 

 

如果报以下错误:


repeater 使用的是无效数据源。有效数据源必须实现 IListSource 或 IEnumerable?

是因为数据源类型问题,比如 DataTable DataSet Xml Arrry  集合
像 String   int   对象 这样的类型是不能直接作为它的数据源的,尤其要注意对象引起的问题


 

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,