在标题后添加Gridview行

Rop*_*tah 5 asp.net gridview row add dynamic

我正在尝试向Gridview添加新的headerrow.此行应显示在原始标题下方.

据我所知,我有两个可供选择的活动:

1.)Gridview_RowDataBound 2.)Gridview_RowCreated

选项1不是一个选项,因为网格没有绑定每个回发上的数据.选项2无法按预期工作.我可以添加行,但它会在HeaderRow之前添加,因为在此事件中尚未添加HeaderRow本身...

请帮忙,谢谢!

代码:(InnerTable属性由自定义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
Run Code Online (Sandbox Code Playgroud)

Rus*_*lan 4

既然这是一个自定义的 GridView,为什么不考虑重写 CreateChildControls 方法呢?

即(对不起,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新 正如 Ropstah 提到的,上面的代码片段在分页打开时不起作用。我将代码移至PrepareControlHierarchy,现在它可以很好地处理分页、选择和排序。

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();
}
Run Code Online (Sandbox Code Playgroud)