[SOLVED] Convert a gridview templatefield to pdf iTextSharp


I have a GridView which is programatically filled from the DB (not a SqlDataSource or such). There are 4 columns which are TemplateFields as I format their text. They are Dates and Times and this is the one of their TemplateField:

     <asp:Label ID="Label1" Text='<%# FormatDate(Eval("tDate")) %>' runat="server"></asp:Label>

This is the function to format that date:

Function FormatDate(objTime As Object) As String
    Dim d As String
    If objTime.Equals(DBNull.Value) Then
        d = ""
        d = Convert.ToDateTime(objTime).ToString("MM-dd-yyyy")
    End If
    Return d
End Function

I’ve been using the method in this Post which was converted to VB code from this to convert the GridView to a PDF using iTextSharp.

My issue is that I’m getting a Null Reference exception here when adding the GridView data to the PDF(inside the For Loops):

Dim lc As DataBoundLiteralControl = TryCast(gvReport.Rows(rowNo).Cells(colNo).Controls(0), DataBoundLiteralControl)
s = lc.Text.Trim()

And if I remove this If statement and just run the Else part here:

s = gvReport.Rows(rowNo).Cells(colNo).Text.Trim()
ph = New Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL))

These Date/Time columns show up as empty on the PDF while all other columns show up with no issues.

I’m very lost on how to resolve this issue and have been unsuccessful in finding a solution online.


While I wasn’t able to fix the solution I was following up above, I found a different way to access data from a TemplateField:

Dim s As String = CType(gvReport.Rows(rowNo).FindControl("Label1"), Label).Text

This gives me access to the data in the specified column. Now I just need to figure out a way iterate through the row and get each of the different TemplateFields which will probably involve reworking my For loops and a Select Case statement.

Answered By – D.Galvez

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *