Search code examples
asp.net.netvb.netdetailsview

Populating textbox based off bound column in DetailsView - Problem with Nulls


I'm trying to populate a date from a bound text field in a DetailsView. I keep getting a error when a DBNull is in the column. How do I avoid the DBNull when populating the text field. Any Help on this would be great at a loss.

My code is as follows:

 <asp:TemplateField HeaderText="CBYD Clear Date">
              <EditItemTemplate>
                  <asp:TextBox ID="CBYDExpDate" runat="server" ReadOnly="true" Text='<%# IIf(Eval("CBYDDate") is DBNull.Value,"", String.Format("{0:MM/dd/yyyy}", Eval("CBYDDate").AddDays(30)))%>' />                                                      
          </EditItemTemplate>
    </asp:TemplateField>

Solution

  • The simpliest would be to define a function in codebehind that you call:

    Text='<%# getDateText(Eval("CBYDDate"),"{0:MM/dd/yyyy}", 30) %>'
    

    and in codebehind:

     Protected Function getDateText(ByVal value As Object, ByVal dateFormatString As String, ByVal addDays As Int32) As String
         If value Is Nothing OrElse value Is DBNull.Value Then
             Return String.Empty
         ElseIf TypeOf value Is Date Then
             Dim d As Date = DirectCast(value, Date)
             Return String.Format(dateFormatString, d.AddDays(addDays))
         Else
             Return value.ToString
         End If
     End Function
    

    For additional informations have a look at MSDN