ASP.NET WebForms 中的 Repeater 控件是一个用于显示重复数据的强大工具。它允许您以模板的方式定义数据项的外观,并根据数据源中的数据重复应用这些模板。以下是一个简单的 ASP.NET WebForms 页面,演示如何使用 Repeater 控件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="YourNamespace.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Repeater Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <!-- 定义 Repeater 控件 -->
            <asp:Repeater ID="repeater1" runat="server">
                <!-- ItemTemplate 定义每个数据项的外观 -->
                <ItemTemplate>
                    <div>
                        <!-- 数据绑定语法用于显示数据项中的字段 -->
                        <h3><%# Eval("ProductName") %></h3>
                        <p>Category: <%# Eval("Category") %></p>
                        <p>Price: $<%# Eval("Price") %></p>
                        <hr />
                    </div>
                </ItemTemplate>
            </asp:Repeater>
        </div>
    </form>
</body>
</html>

在代码文件(WebForm1.aspx.cs)中,您可以在页面加载事件中绑定数据到 Repeater 控件:
using System;
using System.Collections.Generic;
using System.Web.UI;

namespace YourNamespace
{
    public partial class WebForm1 : 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 }
                };

                // 将数据源绑定到 Repeater 控件
                repeater1.DataSource = products;
                repeater1.DataBind();
            }
        }

        // 定义一个简单的数据模型
        public class Product
        {
            public string ProductName { get; set; }
            public string Category { get; set; }
            public double Price { get; set; }
        }
    }
}

这是一个简单的例子,您可以根据实际需求扩展和自定义模板以满足您的项目要求。


转载请注明出处:http://www.zyzy.cn/article/detail/14730/ASP.NET