title: How to draw a grid on a PictureBox preserving the image it contains?
body: <p>I want to draw a grid on the image in a PictureBox.<br>
  But, when the grid is drawn, the image disappears.<br>
  How can I fix this code? It draws the grid when a CheckBox is checked or I change the grid size using a TrackBar.</p>
  
  <pre><code>private void grid()
  {
      int x, y;
      int w = pictureBox1.Size.Width;
      int h = pictureBox1.Size.Height;
      int inc = trackBar1.Value;
  
      BackImage = new Bitmap(w, h);
      Pen myPen = new Pen(Color.Green);
  
      Graphics gr = Graphics.FromImage(BackImage);
      gr.Clear(SystemColors.Control);
  
      if (checkBox1.Checked == true)
      {
          myPen.Color = Color.Green;
  
          for (x = 0; x &lt; w; x += inc)
              gr.DrawLine(myPen, x, pictureBox1.Location.Y, x, h);
  
          for (y = 0; y &lt; h; y += inc)
              gr.DrawLine(myPen, pictureBox1.Location.X, y, w, y);
      }
      Invalidate();
      myPen.Dispose();
  }
  
  private void checkBox1_CheckedChanged(object sender, EventArgs e)
  {
     grid();
      Refresh();
  }
  
  private void trackBar1_Scroll(object sender, EventArgs e)
  {
     grid();
     Refresh();
  }
  
  private void pictureBox1_Paint(object sender, PaintEventArgs e)
  {
      if (BackImage != null)
      e.Graphics.DrawImage(BackImage, 0, 0);
  }
  </code></pre>