pset in

Trying to set a pixel in a picturebox with out any luck.
Please look at the code and tell me what is missing.

If I set the 'bmTemp' to the image of the picturebox, why would I want an new instance as the error message suggests ?  The picture box is empty, but does that mean is has no image at all ?

Public Sub DrawAPixel(ByVal x As Integer, ByVal y As Integer, ByVal clr As Color)

        Dim bmTemp As Bitmap
        bmTemp = pctGraph.Image
        Dim MyClr As Color

        bmTemp.SetPixel(x, y, clr)

    End Sub

Open in new window

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

Meir RivkinConnect With a Mentor Full stack Software EngineerCommented:
>>The picture box is empty, but does that mean is has no image at all ?

yes, that why the error occurs.
u can't set pixels to an empty bitmap.
if u want to create a new bitmap, set its pixels and then assign the bitmap to the picture box u need to create the bitmap first with some parameters:

the code snippet below creates a 50X50 bitmap, set pixels to black and white stripes and then assign to picture box:

Dim bmTemp As New Bitmap(50, 50)

        For X = 0 To bmTemp.Width - 1
            For Y = 0 To bmTemp.Height - 1
                bmTemp.SetPixel(X, Y, If(X Mod 2 = 0, Color.Black, Color.White))
            Next Y
        Next X

        pctGraph.Image = bmTemp

Open in new window

PaulHewsConnect With a Mentor Commented:
The picturebox image property can be assigned a valid image if you wish to display an image.  Until you set it to something it won't have anything.  You can draw on a bitmap, and draw the bitmap on the picturebox like so:
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim bmp As Bitmap = New Bitmap(50, 50)
        For i As Integer = 1 To 10
            For j As Integer = 1 To 10
                bmp.SetPixel(i, j, Color.Red)

        Using g As Graphics = Graphics.FromHwnd(PictureBox1.Handle)
            g.DrawImage(bmp, New Point(0, 0))
        End Using
    End Sub
End Class

Open in new window

sidwelleAuthor Commented:
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could also draw the pixels in the Paint() event of your PictureBox using the supplied "e.Graphics".

Store the data about which pixels to set in a class Level List type structure.

Which approach is better really depends on your application...
All Courses

From novice to tech pro — start learning today.