// class that can draw a grid
class Grid
{
public Grid()
{
// Set some defaults
Origin = new Point(0, 0);
GridCellSize = new Size(10, 10);
HorizontalCells = 1;
VerticalCells = 1;
}
public int HorizontalCells { get; set; }
public int VerticalCells { get; set; }
public Point Origin { get; set; }
public Size GridCellSize { get; set; }
public virtual void Draw(Graphics Graf, Pen pencil)
{
Point startP = new Point();
Point endP = new Point();
// Draw horizontals
startP.X = Origin.X;
endP.X = Origin.X + VerticalCells * GridCellSize.Width;
for (int i = 0; i <= HorizontalCells; i++)
{
startP.Y = Origin.Y + i * GridCellSize.Height;
endP.Y = startP.Y;
Graf.DrawLine(pencil, startP, endP);
}
// Draw verticals
startP.Y = Origin.Y;
endP.Y = Origin.Y + HorizontalCells * GridCellSize.Height;
for (int i = 0; i <= VerticalCells; i++)
{
startP.X = Origin.X + i * GridCellSize.Width;
endP.X = startP.X;
Graf.DrawLine(pencil, startP, endP);
}
}
}
// code for the form
public partial class Form1 : Form
{
Grid thisGrid = new Grid();
public Form1()
{
InitializeComponent();
// Init a grid
thisGrid.Origin = new Point(5, 5);
thisGrid.GridCellSize = new Size(40, 50);
thisGrid.HorizontalCells = 5;
thisGrid.VerticalCells = 7;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// Make some fancy pen, make ANY pen you like here
Pen myPen = new Pen(Color.Blue, 2f);
myPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
myPen.DashCap = System.Drawing.Drawing2D.DashCap.Triangle;
thisGrid.Draw(e.Graphics, myPen);
}
}