Brandontom Brandontom - 8 days ago 5
Vb.net Question

Random Picture generator giving error "reference to a non-shared member requires an object reference"

I need to develop a random picture generator as part of my project and since i'm a newbie i pinched some code of the internet, however it's throwing up the error message "reference to a non-shared member requires an object reference". This is my code:

Dim randnum As random
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
randnum = Random.Next(30)
pbxPicture.Image = My.Resources.ResourceManager.GetObject("Image_" & randnum.ToString())
End Sub


my images in my resources are named "image_0" "image_1" and so on so i hope you see what i'm trying to achieve here, if any one could assist me with this i'd be very grateful :) thanks!

Answer

You must instantiate the randnum variable, then call Next() on that. You also need an Integer variable to put the return value of Next() in.

For clarity I renamed the first variable to rand and let the integer variable have the name randnum instead:

Dim rand As New Random 'Renamed variable and added the "New" keyword.
Dim randnum As Integer = 0 'An Integer variable to hold the result of "rand.Next()".

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    randnum = rand.Next(30)
    pbxPicture.Image = My.Resources.ResourceManager.GetObject("Image_" & randnum.ToString())
End Sub