问题描述
我正在尝试向 Gridview 添加新的标题行.此行应显示在原始标题行下方.
i'm trying to add a new headerrow to a Gridview. This row should appear below the original headerrow.
据我所知,我有两个事件可供选择:
As far as I know I have two events to choose from:
1.) Gridview_RowDataBound2.) Gridview_RowCreated
1.) Gridview_RowDataBound2.) Gridview_RowCreated
选项 1 不是一个选项,因为网格不绑定每个回发的数据.选项 2 没有按预期工作.我可以添加行,但它添加在 HeaderRow 之前,因为在此事件中尚未添加 HeaderRow 本身...
Option 1 is not an option as the grid is not binding the data on each postback.Option 2 does not work as expected. I can add the row, but it is added before the HeaderRow because the HeaderRow itself is not added yet in this event...
请帮忙,谢谢!
代码:(InnerTable 属性由自定义 gridview 公开)
Code: (InnerTable property is exposed by custom gridview)
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
Dim r As New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal)
For Each c As DataControlField In CType(sender, GridView).Columns
Dim nc As New TableCell
nc.Text = c.AccessibleHeaderText
nc.BackColor = Drawing.Color.Cornsilk
r.Cells.Add(nc)
Next
Dim t As Table = GridView1.InnerTable
t.Controls.Add(r)
End If
End Sub
推荐答案
既然这是自定义的 GridView,为什么不考虑覆盖 CreateChildControls 方法?
Since this is a custom GridView, why don't you consider overriding the CreateChildControls method?
即(对不起,C#):
protected override void CreateChildControls()
{
base.CreateChildControls();
if (HeaderRow != null)
{
GridViewRow header = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < Columns.Count; i++)
{
TableCell cell = new TableCell();
cell.Text = Columns[i].AccessibleHeaderText;
cell.ForeColor = System.Drawing.Color.Black;
cell.BackColor = System.Drawing.Color.Cornsilk;
header.Cells.Add(cell);
}
Table table = (Table)Controls[0];
table.Rows.AddAt(1, header);
}
}
更新正如 Ropstah 所提到的,上面的 sniplet 不适用于分页.我将代码移到 PrepareControlHierarchy 中,现在它可以优雅地进行分页、选择和排序.
UPDATEAs was mentioned by Ropstah, the sniplet above does not work with pagination on. I moved the code to a PrepareControlHierarchy and now it works gracefully with pagination, selection, and sorting.
protected override void PrepareControlHierarchy()
{
if (ShowHeader && HeaderRow != null)
{
GridViewRow header = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < Columns.Count; i++)
{
TableCell cell = new TableCell();
cell.Text = Columns[i].AccessibleHeaderText;
cell.ForeColor = System.Drawing.Color.Black;
cell.BackColor = System.Drawing.Color.Cornsilk;
header.Cells.Add(cell);
}
Table table = (Table)Controls[0];
table.Rows.AddAt(1, header);
}
//it seems that this call works at the beginning just as well
//but I prefer it here, since base does some style manipulation on existing columns
base.PrepareControlHierarchy();
}
这篇关于在标题之后添加 Gridview 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!