温馨提示×

使用嵌套的Repeater控件和VisualC#.NET显示分层数据

c#
小云
83
2023-09-08 06:10:38
栏目: 编程语言

可以使用嵌套的Repeater控件和Visual C#.NET来显示分层数据。以下是一个示例:

假设有以下数据结构:

public class Category
{
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public string Name { get; set; }
}

首先,需要在前端页面中添加两个Repeater控件,一个用于显示分类,另一个用于显示产品。在页面上添加以下代码:

<asp:Repeater ID="rptCategories" runat="server">
<ItemTemplate>
<h2><%# Eval("Name") %></h2>
<asp:Repeater ID="rptProducts" runat="server" DataSource='<%# Eval("Products") %>'>
<ItemTemplate>
<p><%# Eval("Name") %></p>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>

然后,在后端代码中绑定数据到Repeater控件。在页面的Page_Load事件中添加以下代码:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Category> categories = GetCategories(); // 获取分类数据
rptCategories.DataSource = categories;
rptCategories.DataBind();
}
}
private List<Category> GetCategories()
{
// 模拟从数据库中获取数据
List<Category> categories = new List<Category>();
Category category1 = new Category
{
Name = "分类1",
Products = new List<Product>()
{
new Product { Name = "产品1" },
new Product { Name = "产品2" },
new Product { Name = "产品3" }
}
};
Category category2 = new Category
{
Name = "分类2",
Products = new List<Product>()
{
new Product { Name = "产品4" },
new Product { Name = "产品5" },
new Product { Name = "产品6" }
}
};
categories.Add(category1);
categories.Add(category2);
return categories;
}

通过以上代码,Repeater控件会根据数据结构进行嵌套显示,首先显示分类名称,然后在每个分类下显示产品名称。这样就实现了分层显示数据的功能。

0