Wednesday, April 15, 2009

El GridView programático … una triste história

Si han seguido un post anterior sobre el gridview programático notaron que todo marchó a pedir de boca.

Pero cuando habilité la paginación del gridview en la webpart apareció este engendro sobrenatural:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.UI.WebControls.GridView.get_StateFormatter() +25


Lo anterior es lo ocurrido cuando el gridview queda configurado para paginación. ¿Pero cómo se logra el error anterior?



Antes





Protected Overrides Sub CreateChildControls() 
           Dim customField As New TemplateField 


            customField.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, "", Me.Imagen, Me.Titulo, Me.Resumen, Me.Contenido) 
            grvPrueba = New GridView() 
             grvPrueba.AutoGenerateColumns = False             grvPrueba .ShowHeader = False             grvPrueba .RowStyle.CssClass = Me.EstiloFila             grvPrueba .AlternatingRowStyle.CssClass = Me.EstiloAlternado 
            If Paginar Then 
                grvPrueba .AllowPaging = Paginar 
                If Me.NumeroRegistros > 0 Then 
                    grvPrueba .PageSize = Me.NumeroRegistros 
                End If 
            End If 
            grvPrueba.Columns.Add(customField) 
            grvPrueba.DataSource = ConsultarLista() 
            grvPrueba.DataBind() 
            AddHandler grvPrueba.PageIndexChanging, AddressOf grvPrueba_PageIndexChanging 
Me.Controls.Add(grvNoticias) 
        End Sub


¿Si han notado que dejo para el final el agregar el gridview a la colección Controls de la webpart? Pues eso es un grave error cuando el gridview permitirá la paginación y cuesta un par de tasas de café y una tarde entera de trabajo perdido. El por qué del error, creo quedo en deuda con la explicación de fondo porque no sé la razón.



Solución



En seguida de la creación del GridView este se debe agregar a la colección Controls de tal forma que nos queda así:



grvPrueba= New GridView()

Me.Controls.Add(grvPrueba)




Feliz GridView programático

No comments: