我有一个 ASP.NET GridView,它的列如下所示:
| Foo | Bar | Total1 | Total2 | Total3 |
是否可以在看起来像这样的两行上创建标题?
| | Totals |
| Foo | Bar | 1 | 2 | 3 |
每行中的数据将保持不变,因为这只是为了美化标题并减少网格占用的水平空间。
整个 GridView 是可排序的,以防万一。我不打算让添加的“总计”跨越列具有任何排序功能。
编辑:
基于下面给出的一篇文章,我创建了一个继承自 GridView 并添加第二个标题行的类。
namespace CustomControls
{
public class TwoHeadedGridView : GridView
{
protected Table InnerTable
{
get
{
if (this.HasControls())
{
return (Table)this.Controls[0];
}
return null;
}
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
this.CreateSecondHeader();
}
private void CreateSecondHeader()
{
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = this.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
this.InnerTable.Rows.AddAt(0, row);
}
}
}
如果您像我一样不熟悉 ASP.NET,我还应该指出您需要:
1)通过在您的网络表单中添加这样的一行来注册您的课程:
<%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
2) 将之前标记中的 asp:GridView 更改为 foo:TwoHeadedGridView。不要忘记结束标签。
另一个编辑:
您也可以在不创建自定义类的情况下执行此操作。
只需为网格的 DataBound 事件添加一个事件处理程序,如下所示:
protected void gvOrganisms_DataBound(object sender, EventArgs e)
{
GridView grid = sender as GridView;
if (grid != null)
{
GridViewRow row = new GridViewRow(0, -1,
DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = grid.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
Table t = grid.Controls[0] as Table;
if (t != null)
{
t.Rows.AddAt(0, row);
}
}
}
自定义控件的优点是您可以在 Web 表单的设计视图中看到额外的标题行。不过,事件处理程序方法要简单一些。