aspx
<asp:GridView ID="GV" runat="server" OnRowCreated="GV_RowCreated">
</asp:GridView>
aspx.cs
protected void GV_RowCreated(object sender, GridViewRowEventArgs e) { // 检查是不是标题列 if (e.Row.RowType == DataControlRowType.Header) { // 建立自订的标题 GridView gv = (GridView)sender; TableCellCollection tcHeader = e.Row.Cells; tcHeader.Clear();//清除自动生成的表头 GridViewRow gvRow1 = Header_Row1(); GridViewRow gvRow2 = Header_Row2(); // 把这一列加到最上面 gv.Controls[0].Controls.AddAt(0, gvRow2); gv.Controls[0].Controls.AddAt(0, gvRow1); } } private GridViewRow Header_Row1() { GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert); // 增加 Department 栏位 TableCell tc1 = new TableCell(); tc1.Text = "Department"; tc1.ColumnSpan = 2; // 跨两栏 tc1.RowSpan = 2; // 跨两栏 Header_置中_粗体(tc1); gvRow.Cells.Add(tc1); // 增加 Employee 栏位 TableCell tc2 = new TableCell(); tc2.Text = "Employee"; tc2.ColumnSpan = 3; // 跨三栏 Header_置中_粗体(tc2); gvRow.Cells.Add(tc2); return gvRow; } private GridViewRow Header_Row2() { GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert); TableCell tc1 = new TableCell(); tc1.Text = "header1"; tc1.ColumnSpan = 1; Header_置中_粗体(tc1); gvRow.Cells.Add(tc1); TableCell tc2 = new TableCell(); tc2.Text = "header2"; tc2.ColumnSpan = 1; Header_置中_粗体(tc2); gvRow.Cells.Add(tc2); TableCell tc3 = new TableCell(); tc3.Text = "header3"; tc3.ColumnSpan = 1; Header_置中_粗体(tc3); gvRow.Cells.Add(tc3); return gvRow; } private static void Header_置中_粗体(TableCell tc2) { tc2.HorizontalAlign = HorizontalAlign.Center; tc2.Font.Bold = true; tc2.Font.Size = 9; }
ref
https://dolphins11.pixnet.net/blog/post/404457859