none
System.NullReferenceException was unhandled RRS feed

  • Question

  • Hi

    Using code below to retrieve my contacts and various user-defined fields from my Outlook contacts and display them on a form

    Most times it works perfectly fine, but every now and then I get a "System.NullReferenceException was unhandled - Object reference not set to an instance of an object." error on the following line:-

    bsContacts.DataSource = MyList.ToDataTable

    Can someone tell me how to avoid this - or how to find out why it does it?

    I can force it to cause error if I amend the following line so it is looking in a contact subfolder

    olConFolder = olNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts

    to

    olConFolder = olNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts).Folders("No contact for 2 years+")

    CODE BELOW:

    Imports Microsoft.Office.Interop.Outlook
    Imports Microsoft.Office.Interop
    
    Public Class Form1
        WithEvents bsContacts As New BindingSource
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
    
            Dim MyList As New List(Of MyContact)
    
            Dim bResult As Boolean = False
            Dim OutlookApp As Outlook.Application = Nothing
            Dim olNameSpace As Outlook.NameSpace
            Dim olConFolder As Outlook.MAPIFolder = Nothing
    
            Dim olConItems As Outlook.Items = Nothing
            Dim olConItem As Outlook.ContactItem
    
            Try
                OutlookApp = New Outlook.Application
                olNameSpace = OutlookApp.GetNamespace("MAPI")
                ' You may need to sign in, I have Outlook open while running this code
                'oNameSpace.Logon( "", "", False, True)
    
                olConFolder = olNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
    
                olConItems = olConFolder.Items
                
                ' variable to hold number of contacts added to list (i.e. after filters applied)
                Dim NumberOfContactsAddedToListBox As Integer = 0
    
                For x As Integer = 1 To olConItems.Count
    
                    If TypeOf olConItems(x) Is ContactItem Then
                        Dim Item As ContactItem = CType(olConItems(x), ContactItem)
                        ' below line can be used to filter list so it doesn't show certain contacts i.e. in this case those labelled as "family/friend" or "non business" in the reason for not mailing field
                        If Not (Item.UserProperties.Find("Reason for not mailing").Value = "Family/Friend") And Not (Item.UserProperties.Find("Reason for not mailing").Value = "Non Business") Then
    
                            ' increments NumberOfContactsAddedToListBox count
                            NumberOfContactsAddedToListBox = NumberOfContactsAddedToListBox + 1
    
                                                    Dim MailingSentDate = Item.UserProperties.Find("Mailing Sent").Value
                            If MailingSentDate = "01/01/4501" Then
                                MailingSentDate = Nothing
                            End If
    
                            Dim DateOfLastVisitDate = Item.UserProperties.Find("Date of last visit").Value
                            If DateOfLastVisitDate = "01/01/4501" Then
                                DateOfLastVisitDate = Nothing
                            End If
    
                            Dim PCHealthCheckDate = Item.UserProperties.Find("Date of Last PC Health Check").Value
                            If PCHealthCheckDate = "01/01/4501" Then
                                PCHealthCheckDate = Nothing
                            End If
    
                            Dim EmailSupportDate = Item.UserProperties.Find("Email Support expires").Value
                            If EmailSupportDate = "01/01/4501" Then
                                EmailSupportDate = Nothing
                            End If
    
                            Dim WebHostingDate = Item.UserProperties.Find("Web Hosting expires").Value
                            If WebHostingDate = "01/01/4501" Then
                                WebHostingDate = Nothing
                            End If
    
                            Dim SearchServiceDate = Item.UserProperties.Find("Search Service expires").Value
                            If SearchServiceDate = "01/01/4501" Then
                                SearchServiceDate = Nothing
                            End If
    
                            MyList.Add(New MyContact With
                                       {
                                           .ContactID = Item.EntryID,
                                           .FileAsName = Item.FileAs,
                                           .EmailAddress = Item.Email1Address,
                                           .MailingStatus = Item.UserProperties.Find("Reason for not mailing").Value,
                                           .MailingSent = MailingSentDate,
                                           .DateOfLastContact = DateOfLastVisitDate,
                                           .Source = Item.UserProperties.Find("Source").Value,
                                           .PCHealthCheck = PCHealthCheckDate,
                                           .EmailSupport = EmailSupportDate,
                                           .WebHosting = WebHostingDate,
                                           .SearchService = SearchServiceDate
                                                             }
                                   )
    
                        End If
                    End If
    
    
                    
                    lblContactCount.Text = NumberOfContactsAddedToListBox & " (" & x & ")"
    
                Next
    
            Finally
                olConItem = Nothing
                olConItems = Nothing
                olConFolder = Nothing
                olNameSpace = Nothing
                OutlookApp = Nothing
            End Try
    
            ' binds the resulting MyList to the bsContacts data source
            bsContacts.DataSource = MyList.ToDataTable
    
            ' shows customer "file as" name in the list box - list box is populated from the bsContacts data source
            lbContactName.DisplayMember = "FileAsName"
            lbContactName.DataSource = bsContacts
    
            ' shows details for customer selected in list box in relevent text box
           
            tbMailingStatus.DataBindings.Add("Text", bsContacts, "MailingStatus")
            tbMailingSent.DataBindings.Add("Text", bsContacts, "MailingSent", True, DataSourceUpdateMode.Never, "d")
            tbSource.DataBindings.Add("Text", bsContacts, "Source")
            tbDateOfLastContact.DataBindings.Add("Text", bsContacts, "DateOfLastContact", True, DataSourceUpdateMode.Never, "d")
            tbPCHealthCheck.DataBindings.Add("Text", bsContacts, "PCHealthCheck", True, DataSourceUpdateMode.Never, "d")
            tbEmailSupport.DataBindings.Add("Text", bsContacts, "EmailSupport", True, DataSourceUpdateMode.Never, "d")
            tbWebHosting.DataBindings.Add("Text", bsContacts, "WebHosting", True, DataSourceUpdateMode.Never, "d")
            tbSearchService.DataBindings.Add("Text", bsContacts, "SearchService", True, DataSourceUpdateMode.Never, "d")
    
            ' sorts results into alphabetical order
            bsContacts.Sort = "FileAsName"
    
        End Sub
    
    
    
            Private Sub btnSortASC_Click(sender As Object, e As EventArgs) Handles btnSortASC.Click
            bsContacts.Sort = "FileAsName"
        End Sub
        Private Sub btnSortDESC_Click(sender As Object, e As EventArgs) Handles btnSortDESC.Click
            bsContacts.Sort = "FileAsName DESC"
        End Sub
    
    End Class
    
    
    Public Class MyContact
        Public Property FileAsName As String
        Public Property EmailAddress As String
        Public Property ContactID As String
    
        Public Property MailingStatus As String
        Public Property Source As String
        Public Property MailingSent As DateTime
        Public Property DateOfLastContact As DateTime
        Public Property EmailSupport As DateTime
        Public Property WebHosting As DateTime
        Public Property SearchService As DateTime
        Public Property PCHealthCheck As DateTime
    
      End Class


    Darren Rose

    Wednesday, October 15, 2014 3:22 PM

All replies

  • Hello Daren,

    The NullReferenceException is thrown when there is an attempt to dereference a null object reference. You need to check objects for null (Nothing in VB.NET). I'd recommend spending some time under the debugger and see what happens, i.e. what method or property returns null.

    Wednesday, October 15, 2014 3:28 PM
  • Yes I had guessed it must be something to do with one of the fields being empty - and have looked through the 403 contacts in that folder in outlook and all fields are complete?

    As it seems to scan through all 403 contacts before giving me the error, how can I EASILY find out cause, as I can't see it telling me anything useful in debugger


    Darren Rose

    Wednesday, October 15, 2014 3:41 PM
  • just tried it with a contact sub-folder containing only 8 entries - and same error - and definitely no null values in any of the fields being retrieved as manually checked the 8 contacts

    Perhaps it is something to do with using .folders("fhfghfg") to look in a sub-folder? although it does happen with main contacts folder, but not all the time, and data doesn't change in between so hence why confused as to cause


    Darren Rose

    Wednesday, October 15, 2014 3:52 PM
  • Darren,

    I'd recommend breaking the chain of calls (multiple dots in the single line of code) and declare each property or method call on a separate line of code. Thus, you will be able to find the cause.


    Wednesday, October 15, 2014 4:36 PM
  • Thanks Eugene

    From fiddling around and moving bits of code I found it was the email1address field causing the null reference exception - which is strange as it works okay on main contacts folder even though I have several contacts with no email addresses - but on the sub-folders it cause the error

    Amended code to check contents of Email1Address and if null/empty then set it to NO EMAIL

    Dim EmailAddress = Item.Email1Address
    If String.IsNullOrEmpty(EmailAddress) Then
          EmailAddress = "NO EMAIL"
    End If

    This seems to work, but still confused as to why not an issue on main folder, just sub-folders

    But it is working for now....


    Darren Rose

    Wednesday, October 15, 2014 4:41 PM
  • Hi Darren Rose,

    The issue seems strange that only occur in the sub folders. I suspected this issue may relative to the data context, I suggest that a new folder and add some contacts to see whether this issue could be reproduced.

    Hope it is helpful.

    Best regards

    Fei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, October 22, 2014 9:20 AM
    Moderator