我有一個ASP.NET的GridView它有看起來像這樣的列: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)註冊你的課程,在你的web表格中加入這樣一行:
<%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
2)將你以前的標記中的asp:GridView改爲foo:TwoHeadedGridView。不要忘記結束標籤。
另一個編輯:
你也可以做到這一點,而無需創建一個自定義類。
只需添加一個事件處理程序爲網格的類似這樣的數據綁定事件:
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表單的設計視圖中的額外的標題行。不過,事件處理程序方法有點簡單。
更新的答案已經幫助我很多,非常感謝您抽出時間來記錄它 – Alex 2009-11-12 17:20:11
同樣在這裏 - 感謝填空題 – CResults 2011-06-02 11:18:01
注 - 我發現我不得不添加`row.TableSection = TableRowSection .TableHeader`代碼無誤地工作 – CResults 2011-06-02 14:20:24