Pregunta

Estoy tratando de añadir un nuevo headerrow a un GridView. Esta fila debe aparecer debajo de la headerrow originales.

Por lo que yo sé que tengo dos eventos para elegir:

1.) Gridview_RowDataBound 2.) Gridview_RowCreated

Opción 1 no es una opción como la rejilla no es vinculante los datos sobre cada una devolución de datos. Opción 2 no funciona como se esperaba. Puedo añadir la fila, pero se añade antes de la HeaderRow porque el propio HeaderRow no se añade sin embargo, en este caso ...

Por favor, ayudar, gracias!

Código: (propiedad InnerTable se expone por gridview personalizado)

    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
¿Fue útil?

Solución

Dado que este es un GridView costumbre, ¿por qué no se tiene en cuenta reemplazando el método CreateChildControls?

es decir (lo siento, 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);
    }
}

Actualizar Como se ha mencionado por Ropstah, la sniplet anterior no funciona con paginación sucesivamente. Moví el código a un PrepareControlHierarchy y ahora funciona con gracia con paginación, selección y clasificación.

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();
}

Otros consejos

Los buenos chicos de trabajo, que utilizan su técnica para agrupar mi gridview permitido AJAX, y lo buscaron durante mucho, mucho tiempo. Saludos.

protected override void PrepareControlHierarchy()
{
    if (GroupColumns)
    {
        #region Group Column

        Table table = (Table)Controls[0];

        string lastValue = string.Empty;
        foreach (GridViewRow gvr in this.Rows)
        {
            string currentValue = gvr.Cells[GroupColumnIndex].Text;

            if (lastValue.CompareTo(currentValue) != 0)
            {
                // there's been a change in value in the sorted column
                int rowIndex = table.Rows.GetRowIndex(gvr);

                // Add a new sort header row
                GridViewRow sortRow = new GridViewRow(rowIndex, rowIndex, DataControlRowType.DataRow, DataControlRowState.Normal);

                TableCell sortCell = new TableCell();
                TableCell blankCell = new TableCell();

                sortCell.ColumnSpan = this.Columns.Count - 1;
                sortCell.Text = string.Format("{0}", currentValue);

                blankCell.CssClass = "group_header_row";
                sortCell.CssClass = "group_header_row";

                // Add sortCell to sortRow, and sortRow to gridTable
                sortRow.Cells.Add(blankCell);
                sortRow.Cells.Add(sortCell);
                table.Controls.AddAt(rowIndex, sortRow);

                // Update lastValue
                lastValue = currentValue;
            }
        }

        #endregion
    }

    HideColumns();

    base.PrepareControlHierarchy();
} 

Probar cuando se agrega la fila a la InnerTable:

t.Controls.AddAt(1, r)

Esta es una prueba básica rápida que hice, que parece funcionar bien:

Protected Sub gridview_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridview.DataBound
    Dim g As GridView = CType(sender, GridView)

    Dim r As New GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal)
    Dim th As New TableHeaderCell()
    th.ColumnSpan = g.Columns.Count
    th.Text = "This is my new header"
    r.Cells.Add(th)

    Dim t As Table = CType(g.Controls(0), Table)
    t.Rows.AddAt(1, r)
End Sub
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top