您的位置:首页 > 编程语言 > ASP

asp.net GridView多行表头的实现,合并表头

2014-12-13 09:06 387 查看
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
TableCellCollection tcHeader = e.Row.Cells;
//获取表头所在行的所有单元格

//清除自动生成的表头
tcHeader.Clear();

//新添加的第一个表头单元格, 设置为合并7个列, 从而形成一行.
tcHeader.Add(new TableHeaderCell());
tcHeader[0].ColumnSpan = 7;
tcHeader[0].Text = "测试多行合并表头</th></tr><tr>";
//</th>表示当前单元格结束, </tr>表示本行结束, <tr>另起新一行    关键点

//添加第二个表头单元格, 设置为合并两行.
tcHeader.Add(new TableHeaderCell());
tcHeader[1].RowSpan = 2;
tcHeader[1].Text = "表头";
tcHeader.Add(new TableHeaderCell());
tcHeader[2].Text = "表头1";

tcHeader.Add(new TableHeaderCell());
tcHeader[3].ColumnSpan = 2;
tcHeader[3].Text = "表头2";

tcHeader.Add(new TableHeaderCell());
tcHeader[4].ColumnSpan = 3;
tcHeader[4].Text = "表头3</th></tr><tr>";
//第二行的所有的单元格添加完成, 换行</th></tr><tr>

//添加第三行所有的单元格
tcHeader.Add(new TableHeaderCell());
tcHeader[5].Text = "表头1-1";

tcHeader.Add(new TableHeaderCell());
tcHeader[6].Text = "表头2-1";

tcHeader.Add(new TableHeaderCell());
tcHeader[7].Text = "表头2-2";

tcHeader.Add(new TableHeaderCell());
tcHeader[8].Text = "表头3-1";

tcHeader.Add(new TableHeaderCell());
tcHeader[9].Text = "表头3-2";

tcHeader.Add(new TableHeaderCell());
tcHeader[10].Text = "表头3-3</th></tr><tr>";

}

}

第二种方法

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: