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

如何在ASP.NET+C#的GridView中使用colspan实现记录分组分隔

实现方案

最终实现效果和你给出的示例一致:
分组分隔行效果示例

前置要求

绑定数据前请先将数据源按Code字段排序,保证同Code的记录连续排列,否则会出现分组错乱的问题。

完整可运行代码

DataTable dt = grd1.ToDataTable(objList);
// 按Code排序保证同组数据连续
dt.DefaultView.Sort = "Code ASC";
dt = dt.DefaultView.ToTable();
grd1.DataBind(dt);

// 原有前景色设置逻辑保留
foreach (GridViewRow row in grd1.Rows)
{
    for (int i = 0; i < grd1.Columns.Count; i++)
    {
        TableCell cell = row.Cells[i];
        cell.ForeColor = Color.FromArgb(Convert.ToInt32(dt.Rows[row.RowIndex]["Color"]));
    }
}

// 倒序遍历行插入分隔行,避免插入操作影响未遍历行的索引
string lastCode = string.Empty;
for (int i = grd1.Rows.Count - 1; i >= 0; i--)
{
    string currentCode = dt.Rows[i]["Code"].ToString();
    // 和上一行Code不同时,在当前行上方插入分隔行
    if (i != grd1.Rows.Count - 1 && currentCode != lastCode)
    {
        GridViewRow sepRow = new GridViewRow(i + 1, i + 1, DataControlRowType.DataRow, DataControlRowState.Normal);
        TableCell sepCell = new TableCell();
        sepCell.ColumnSpan = grd1.Columns.Count;
        // 自定义分隔行文本,按需修改即可
        sepCell.Text = $"--- 分组:Code = {currentCode} ---";
        // 自定义分隔行样式
        sepCell.BackColor = Color.FromArgb(240,240,240);
        sepCell.Font.Bold = true;
        sepCell.HorizontalAlign = HorizontalAlign.Left;
        sepRow.Cells.Add(sepCell);
        grd1.Controls[0].Controls.AddAt(i + 2, sepRow);
    }
    lastCode = currentCode;
}

// 可选:给第一组也加顶部标题
if (grd1.Rows.Count > 0)
{
    string firstCode = dt.Rows[0]["Code"].ToString();
    GridViewRow firstSepRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
    TableCell firstSepCell = new TableCell();
    firstSepCell.ColumnSpan = grd1.Columns.Count;
    firstSepCell.Text = $"--- 分组:Code = {firstCode} ---";
    firstSepCell.BackColor = Color.FromArgb(240,240,240);
    firstSepCell.Font.Bold = true;
    firstSepCell.HorizontalAlign = HorizontalAlign.Left;
    firstSepRow.Cells.Add(firstSepCell);
    grd1.Controls[0].Controls.AddAt(1, firstSepRow);
}

自定义调整说明

  • 如果只需要纯分隔线不需要文本,把Text属性设为空,再给sepCell设置Height和BorderBottom样式即可
  • 分隔行的背景色、字体、对齐方式都可以按需修改
  • Code字段如果是数值类型,可以直接做数值比较,不需要转字符串

内容的提问来源于stack exchange,提问作者aditya khot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:24:01