You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Asp.net C#中合并Repeater控件相同列值的重复行

适配Repeater控件实现相同值行合并的方案

没问题,我帮你把原来GridView的行合并逻辑改成适配Repeater控件的版本!Repeater不像GridView有现成的Rows集合,所以我们需要调整处理时机和控件获取方式,以下是具体实现步骤:

1. 前端Repeater模板配置

首先要在Repeater的ItemTemplate里给需要合并的列控件设置明确的ID,方便后台定位:

<asp:Repeater ID="rpt_popup_details" runat="server" OnPreRender="rpt_popup_details_PreRender">
    <HeaderTemplate>
        <table border="1" cellpadding="4" cellspacing="0">
            <tr>
                <th>需要合并的列</th>
                <th>列1</th>
                <th>列2</th>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <!-- 给合并列的Literal设置ID,方便后台定位 -->
            <td><asp:Literal ID="lit_MergeColumn" runat="server" Text='<%# Eval("你的合并列字段名") %>'></asp:Literal></td>
            <td><%# Eval("字段名1") %></td>
            <td><%# Eval("字段名2") %></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

2. 后台合并逻辑实现

我们选择在Repeater的PreRender事件中处理合并(此时所有项都已绑定完成,控件实例化完毕),逻辑和你原来的GridView版本保持一致:

protected void rpt_popup_details_PreRender(object sender, EventArgs e)
{
    // 如果项数小于等于1,无需合并
    if (rpt_popup_details.Items.Count <= 1) return;

    int rowSpan = 2;
    // 从倒数第二项往前遍历,累计合并行数
    for (int i = rpt_popup_details.Items.Count - 2; i >= 0; i--)
    {
        RepeaterItem currentItem = rpt_popup_details.Items[i];
        RepeaterItem previousItem = rpt_popup_details.Items[i + 1];

        // 获取当前项和前一项的合并列控件
        Literal currentLit = currentItem.FindControl("lit_MergeColumn") as Literal;
        Literal previousLit = previousItem.FindControl("lit_MergeColumn") as Literal;

        if (currentLit != null && previousLit != null && currentLit.Text == previousLit.Text)
        {
            // 获取当前项的<td>元素,设置RowSpan
            HtmlTableCell currentTd = currentLit.Parent as HtmlTableCell;
            if (currentTd != null)
            {
                currentTd.RowSpan = rowSpan;
                // 隐藏前一项的<td>
                HtmlTableCell previousTd = previousLit.Parent as HtmlTableCell;
                if (previousTd != null)
                {
                    previousTd.Visible = false;
                }
                rowSpan++;
            }
        }
        else
        {
            // 遇到不同值,重置合并行数
            rowSpan = 2;
        }
    }
}

关键说明

  • 选择PreRender事件是因为此时Repeater的所有Item都已完成数据绑定,能准确获取每个项的内容和控件实例;
  • 遍历方向和你原来的GridView逻辑一致(从后往前),这样可以方便累计合并的行数,避免重复计算;
  • 必须确保合并列的控件(比如lit_MergeColumn)的父元素是<td>,这样才能通过Parent属性获取到HtmlTableCell来设置RowSpan和Visible属性。

内容的提问来源于stack exchange,提问作者hazel Upadhyay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:57:39