【发布时间】:2010-09-23 19:19:21
【问题描述】:
我有一个 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 表单的设计视图上看到额外的标题行。不过,事件处理程序方法要简单一些。
【问题讨论】:
-
更新后的答案对我有很大帮助,感谢您花时间记录它
-
这里相同 - 感谢您填写空白
-
注意 - 我发现我必须添加
row.TableSection = TableRowSection.TableHeader才能使代码正常工作