在.NET开发中,Repeater是一个数据绑定控件,用于显示重复的数据项列表。struct(结构体)是值类型,通常用于表示简单的数据结构。将struct类型的通用列表(List<struct>)绑定到Repeater控件是一种常见的数据展示需求。
首先定义一个简单的struct类型:
public struct Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
创建struct类型的List作为数据源:
List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Mouse", Price = 19.99m },
new Product { Id = 3, Name = "Keyboard", Price = 49.99m }
};
在ASP.NET Web Forms中绑定数据:
repeaterProducts.DataSource = products;
repeaterProducts.DataBind();
<asp:Repeater ID="repeaterProducts" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Id") %></td>
<td><%# Eval("Name") %></td>
<td><%# Eval("Price", "{0:C}") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
如果数据结构较复杂或需要频繁修改,可以考虑使用class代替struct:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
绑定方式与struct相同,但避免了装箱操作,更适合复杂场景。
问题1:数据绑定后显示为空
问题2:Eval表达式无法获取值
问题3:性能问题
没有搜到相关的文章