roadmaster
roadmaster

Reputation: 603

Drawing a Grid of Dots on a PictureBox in C#

I have been searching for about 12 hours now trying to find a way to draw dots on a PictureBox, I've found many threads giving example code and yet I just can't seem to get done what I want.

In essance what I am trying to do is this:

I have a windows form with a PictureBox on it, I do not have any Image in the PictureBox, however I do have the BackColor set to Black. I am trying to create a new bitmap image then run code to create white dots in the following style:

    ..........
    ..........
    ..........
    ..........

Thus giving me a grid style Look on the PictureBox. However at every attempt I have failed, so if anyone could help me understand how to work with this I would appreciate it.

My most recent attempt was to use the ControlPaint.DrawGrid Method, like so:

private void picBox_Display_Paint(object sender, PaintEventArgs e)
{
    Size size = new Size(35, 35);
    Rectangle rect = new Rectangle(0,0,picBox_Display.Width, picBox_Display.Height);
    ControlPaint.DrawGrid(Graphics.FromHwnd(picBox_Display.Handle), rect, size, Color.White);
}

The above code is in the PictureBox Paint event method. I know it runs through the code because I have a breakpoint at the end of the method, but nothing happens. I'm not sure I understand how the ControlPaint.DrawGrid works am I supposed to be adding something else?

I tried using the Bitmap.SetPixel method earlier today but kept having issues with it and kept looking for other ways to try to get it done.

Any help would be appreciated. Thanks!

Upvotes: 0

Views: 2691

Answers (1)

MikeKulls
MikeKulls

Reputation: 3049

You need to use e.Graphics for this. Note also that debugging this sort of code can be difficult because debugging often invalidates the drawing so it needs to be drawn again. The last parameter is meant to be the background color against what you are painting, so it looks like it draws the opposite of what you specify. If you background is black you need to pass in Color.Black

ControlPaint.DrawGrid(e.Graphics, rect, size, Color.Black);

Upvotes: 1

Related Questions