Click here to Skip to main content
15,880,972 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

VB
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

Two bugs are obvious:

Instead of
VB
For i = 0 To bookmarks.Count 
should be
VB
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
 
Share this answer
 
v2
Comments
OrangeFlash81 19-Mar-13 14:11pm    
Thanks a bunch, works!
Sergey Alexandrovich Kryukov 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
Change

VB
Dim fav As ToolStripMenuItem

to
VB
Dim fav As New ToolStripMenuItem()


Basically you are trying to use an item you have not initialised.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900