實現方法就是給單元格填充我們想要的格式代碼。
protected void page_load( object sender, eventargs e )
{
if (!ispostback)
{
gridview1.bordercolor = system.drawing.color.darkorange;
gridview1.datasource = createdatasource();
gridview1.databind();
}
}
protected void gridview1_rowcreated( object sender, gridviewroweventargs e )
{
if (e.row.rowtype == datacontrolrowtype.header)
{
//創建一個gridviewrow,相當于表格的 tr 一行
gridviewrow rowheader = new gridviewrow(0, 0, datacontrolrowtype.header, datacontrolrowstate.normal);
string headerbackcolor = "#ededed";
rowheader.backcolor = system.drawing.colortranslator.fromhtml(headerbackcolor);
//實現確定要顯示的表頭樣式,也可以通過計算生成
// <tr>
// <td rowspan='2'>關鍵單元格</td>
// <td colspan='2'>表頭文字</td>
// <td colspan='2'>表頭文字</td>
// <td>表頭文字</td>
// </tr>
// <tr bgcolor='#fff'>
// <td colspan='2'>表頭文字</td>
// <td rowspan='2'>表頭文字</td>
// <td colspan='2'>表頭文字</td>
// </tr>
// <tr bgcolor='#fff'>
// <td>表頭文字</td>
// <td>表頭文字</td>
// <td>表頭文字</td>
// <td>表頭文字</td>
// <td>表頭文字</td>";
// </tr>
// 上面的樣式可以設置斜線
literal newcells = new literal();
newcells.text = @"表頭文字1</th>
<th colspan='2'>表頭文字2</th>
<th colspan='2'>表頭文字3</th>
<th>表頭文字4</th>
</tr>
<tr bgcolor='" + headerbackcolor + "'>";
newcells.text += @"
<th colspan='2'>表頭文字5</th>
<th rowspan='2'>表頭文字6</th>
<th colspan='2'>表頭文字7</th>
</tr>
<tr bgcolor='" + headerbackcolor + "'>";
newcells.text += @"
<th>表頭文字8</th>
<th>表頭文字9</th>
<th>表頭文字10</th>
<th>表頭文字11</th>
<th>表頭文字12";
tablecellcollection cells = e.row.cells;
tableheadercell headercell = new tableheadercell();
//下面的屬性設置與 <td rowspan='2'>關鍵單元格</td> 要一致
headercell.rowspan = 2;
headercell.controls.add(newcells);
rowheader.cells.add(headercell);
rowheader.cells.add(headercell);
rowheader.visible = true;
//添加到 gridview1
gridview1.controls[0].controls.addat(0, rowheader);
}
}
protected void gridview1_rowdatabound( object sender, gridviewroweventargs e )
{
if (e.row.rowtype == datacontrolrowtype.header)
{
e.row.attributes.add("style", "background:#9999ff;color:#ffffff;font-size:14px");
}
else
{
e.row.attributes.add("style", "background:#fff");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>為 gridview 添加多層表頭</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview id="gridview1" runat="server" cellspacing="1" cellpadding="3" font-size="12px"
width="600px" backcolor="#000000" borderwidth="0" onrowdatabound="gridview1_rowdatabound"
onrowcreated="gridview1_rowcreated">
</asp:gridview>
</form>
</body>
</html>
新聞熱點
疑難解答
圖片精選