Click here to Skip to main content
11,805,604 members (47,775 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: VB VB.NET VS2012

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 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.
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
0 OriginalGriff 300
1 Richard Deeming 225
2 Sergey Alexandrovich Kryukov 170
3 ppolymorphe 125
4 CPallini 120
0 OriginalGriff 3,265
1 Maciej Los 1,990
2 KrunalRohit 1,907
3 CPallini 1,855
4 Richard MacCutchan 1,227

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 19 Mar 2013
Copyright © CodeProject, 1999-2015
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