实现方法就是给单元格填充我们想要的格式代码。
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>
新闻热点
疑难解答
图片精选