Thursday, November 27, 2008

Date Formatting in GridView BoundField

Quick note on this – spent a few minutes on getting this to work. 

Formatting a date field value on a ASP:GridView did not work initially. I had a function that returns a bound field as given below. But No matter what I did, I could not get the formatting of the field to work.

 Say for instance I set the format string as {0:mm-dd-yyyy}. It would still display the field in the default long format. Until I set the "HtmlEncode" to False, which saved me some time:


    Public Function GetBoundField( _

              ByVal dataField As String _

            , ByVal headerText As String _

            , ByVal headerStyle As String _

            , ByVal itemStyle As String _

            , ByVal dataFormatString As String _

            ) As BoundField


        Dim bf As BoundField = Nothing


        bf = New BoundField

        With bf

            .DataField = dataField

            .HeaderText = headerText

            .HeaderStyle.CssClass = headerStyle

            .ItemStyle.CssClass = itemStyle

            .HtmlEncode = False

            .DataFormatString = dataFormatString

        End With

        Return bf

    End Function

No comments: