DataGrid 本質渲染為 HTML <table>,多維表頭即合併儲存格(rowspan/colspan)。利用 ItemDataBound 事件在 Header 行操作 Cells 集合即可實現。
<asp:DataGrid ID="DataGrid1" runat="server"
OnItemDataBound="DataGrid1_ItemDataBound">
</asp:DataGrid>
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string sql = "SELECT EmpID, Name, BranchID, LoginID, Pwd, Sex, EmpCode, Email, OfficeTel FROM mrBaseInf";
using (SqlConnection con = new SqlConnection("server=.;database=iOffice2009;uid=sa;pwd=sa")) {
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
}
}
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e) {
// 僅處理表頭行
if (e.Item.ItemType == ListItemType.Header) {
// 前 5 列跨 2 行
for (int i = 0; i <= 4; i++) {
e.Item.Cells[i].RowSpan = 2;
}
// 第 6 列(索引 5)跨 4 列,作為組標題
e.Item.Cells[5].ColumnSpan = 4;
e.Item.Cells[5].HorizontalAlign = HorizontalAlign.Center;
// 關鍵:直接注入 HTML 片段構建次級表頭
e.Item.Cells[5].Text = "測試</td></tr><tr><td>列1</td><td>列2</td><td>列3</td><td>列4</td></tr>";
// 隱藏被合併的儲存格(索引 6,7,8 對應原第 7,8,9 列)
e.Item.Cells[6].Visible = false;
e.Item.Cells[7].Visible = false;
e.Item.Cells[8].Visible = false;
}
}

| 技術點 | 說明 |
|---|---|
| RowSpan | 垂直合併儲存格,跨越指定行數 |
| ColumnSpan | 水平合併儲存格,跨越指定列數 |
| Cells 集合索引 | 合併後原有儲存格仍存在,需設 Visible=false 隱藏 |
| Text 注入 HTML | 利用瀏覽器容錯解析,在儲存格中插入 </td></tr><tr>... 強制換行 |
| HorizontalAlign | 設定組標題水平居中 |
DataGrid 為 ASP.NET 1.x 遺留控件,建議新專案使用 GridView:
RowSpan/ColSpan 更語義化的屬性RowDataBound 等)public static void MergeHeaderCells(GridView gv, int[] rowSpanCols, int colSpanIndex, int colSpanCount, string groupHeaderHtml) {
gv.RowDataBound += (s, e) => {
if (e.Row.RowType == DataControlRowType.Header) {
foreach (int idx in rowSpanCols) e.Row.Cells[idx].RowSpan = 2;
e.Row.Cells[colSpanIndex].ColumnSpan = colSpanCount;
e.Row.Cells[colSpanIndex].Text = groupHeaderHtml;
for (int i = colSpanIndex + 1; i < colSpanIndex + colSpanCount; i++)
e.Row.Cells[i].Visible = false;
}
};
}
使用:MergeHeaderCells(grid, new[]{0,1,2,3,4}, 5, 4, "測試</td></tr><tr>...");