<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="YourNamespace.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataList Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<!-- 定义 DataList 控件 -->
<asp:DataList ID="dataList1" runat="server" RepeatColumns="3">
<!-- ItemTemplate 定义每个数据项的外观 -->
<ItemTemplate>
<div style="border: 1px solid #ccc; padding: 10px; margin: 5px;">
<!-- 数据绑定语法用于显示数据项中的字段 -->
<h3><%# Eval("ProductName") %></h3>
<p>Category: <%# Eval("Category") %></p>
<p>Price: $<%# Eval("Price") %></p>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
在代码文件(WebForm2.aspx.cs)中,您可以在页面加载事件中绑定数据到 DataList 控件:
using System;
using System.Collections.Generic;
using System.Web.UI;
namespace YourNamespace
{
public partial class WebForm2 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 模拟数据源
List<Product> products = new List<Product>
{
new Product { ProductName = "Product 1", Category = "Category A", Price = 19.99 },
new Product { ProductName = "Product 2", Category = "Category B", Price = 29.99 },
new Product { ProductName = "Product 3", Category = "Category A", Price = 39.99 },
new Product { ProductName = "Product 4", Category = "Category C", Price = 49.99 },
new Product { ProductName = "Product 5", Category = "Category B", Price = 59.99 },
new Product { ProductName = "Product 6", Category = "Category A", Price = 69.99 }
};
// 将数据源绑定到 DataList 控件
dataList1.DataSource = products;
dataList1.DataBind();
}
}
// 定义一个简单的数据模型
public class Product
{
public string ProductName { get; set; }
public string Category { get; set; }
public double Price { get; set; }
}
}
}
这个例子中,DataList 控件会将数据按照指定的列数(RepeatColumns 属性)进行排列显示。您可以根据实际需求调整模板和样式。
转载请注明出处:http://www.pingtaimeng.com/article/detail/14731/ASP.NET