我有一个ASP.NET GridView,其中的列如下所示:
| Foo | Bar | Total1 | Total2 | Total3 |
可以在两行上创建一个如下所示的标题吗?
| | Totals |
| Foo | Bar | 1 | 2 | 3 |
每一行中的数据都将保持不变,因为这只是为了修饰标题并减少网格占用的水平空间.
整个GridView都是可排序的,以备不时之需.我不希望添加的"总计"跨越列具有任何排序功能.
Edit:
基于下面给出的其中一篇文章,我创建了一个从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) 通过在web表单中添加以下行来注册课程:
<%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
2)将前面标记中的asp:GridView更改为foo:TwoHeadedGridView.别忘了结束标签.
Another edit:个
也可以在不创建自定义类的情况下执行此操作.
只需为网格的数据绑定事件添加一个事件处理程序,如下所示:
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表单的设计视图上看到额外的标题行.不过,事件处理程序方法要简单一些.