我有一个ASP.NET GridView,它有如下所示的列:
| Foo | Bar | Total1 | Total2 | Total3 |
是否可以在两行上创建一个看起来像这样的标题?
| | Totals | | Foo | Bar | 1 | 2 | 3 |
每行中的数据将保持不变,因为这只是使标题更漂亮并减少网格占用的水平空间.
如果重要的话,整个GridView都是可排序的.我不打算为添加的"Totals"生成列添加任何排序功能.
编辑:
基于下面给出的一篇文章,我创建了一个继承自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.不要忘记结束标记.
另一个编辑:
您也可以在不创建自定义类的情况下执行此操作.
只需为网格的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表单的设计视图中看到额外的标题行.但是,事件处理程序方法稍微简单一些.
本文应指出正确的方向.您可以以编程方式创建行并将其添加到位置0的集合中.
我接受了接受的答案方法,但是将标题添加到现有的GridView而不是自定义继承的GridView.
绑定GridView后,我执行以下操作:
/*Create header row above generated header row*/ //create row GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); //spanned cell that will span the columns I don't want to give the additional header TableCell left = new TableHeaderCell(); left.ColumnSpan = 6; row.Cells.Add(left); //spanned cell that will span the columns i want to give the additional header TableCell totals = new TableHeaderCell(); totals.ColumnSpan = myGridView.Columns.Count - 3; totals.Text = "Additional Header"; row.Cells.Add(totals); //Add the new row to the gridview as the master header row //A table is the only Control (index[0]) in a GridView ((Table)myGridView.Controls[0]).Rows.AddAt(0, row); /*fin*/