Click here to Skip to main content
13,050,904 members (64,247 online)
Rate this:
Please Sign up or sign in to vote.
See more:

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)
End Sub

Any help would be appreciated.


Posted 19-Mar-13 7:59am
Rate this: bad
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,
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2


Dim fav As ToolStripMenuItem

Dim fav As New ToolStripMenuItem()

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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170713.1 | Last Updated 19 Mar 2013
Copyright © CodeProject, 1999-2017
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