Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
Hello!
 
I am attempting to debug a small internet browser project, but attempting to list favourites from a StringCollection results in a NullReferenceException. Here is my code:
 
    Private Sub ToolStripDropDownButton1_Click(sender As Object, e As EventArgs) Handles ToolStripDropDownButton1.Click
        bookmarks = My.Settings.favourites
        For i = 0 To bookmarks.Count
            Dim ii As Int32 = i
            Dim fav As ToolStripMenuItem <--- Where I get the exception
            fav.ToolTipText = bookmarks.Item(ii)
            ToolStripDropDownButton1.DropDownItems.Add(fav)
        Next
    End Sub
 
Any help would be appreciated.
 
Thanks!
 
-Orange
Posted 19-Mar-13 8:59am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Two bugs are obvious:
 
Instead of
For i = 0 To bookmarks.Count 
should be
For i = 0 To bookmarks.Count - 1
 
And fav is not initialized. (This is VB.NET defect; in C# it would not compile.)
 
This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.
 
Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].
 
Good luck,
—SA
  Permalink  
v2
Comments
OrangeFlash81 at 19-Mar-13 14:11pm
   
Thanks a bunch, works!
Sergey Alexandrovich Kryukov at 19-Mar-13 14:13pm
   
It's a pleasure to help someone who can actually use the help and makes things working.
Good luck, call again.
—SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Change
 
Dim fav As ToolStripMenuItem
to
Dim fav As New ToolStripMenuItem()
 
Basically you are trying to use an item you have not initialised.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 6,569
1 Sergey Alexandrovich Kryukov 6,168
2 DamithSL 5,228
3 Manas Bhardwaj 4,717
4 Maciej Los 4,150


Advertise | Privacy | Mobile
Web04 | 2.8.1411022.1 | Last Updated 19 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100