I have created a Windows UserControl. It actually paints a Grid (i.e. vertical and horizontal lines) using Graphics. User can change each cell height and width, and according to that Grid is refreshed. Overriding the OnPaint event I have created the grid. I used SetStyle(ControlStyles.Opaque, true) to make it transparent. I used this control on a form and from there I change the values of the cell height and width but due to Opaque the new grid is overlapping on the previous one and making it clumsy. How do I resolve this?
UserControl Code:
public partial class Grid : UserControl
{
public Grid()
{
InitializeComponent();
SetStyle(ControlStyles.Opaque, true);
}
private float _CellWidth = 10, _CellHeight = 10;
private Color _GridColor = Color.Black;
public float CellWidth
{
get
{
return this._CellWidth;
}
set
{
this._CellWidth = value;
}
}
public float CellHeight
{
get
{
return this._CellHeight;
}
set
{
this._CellHeight = value;
}
}
public Color GridColor
{
get
{
return this._GridColor;
}
set
{
this._GridColor = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g;
float iHeight = this.Height;
float iWidth = this.Width;
g = e.Graphics;
Pen myPen = new Pen(GridColor);
myPen.Width = 1;
if (this.CellWidth > 0 && this.CellHeight > 0)
{
for (float X = 0; X <= iWidth; X += this.CellWidth)
{
g.DrawLine(myPen, X, 0, X, iHeight);
}
for (float Y = 0; Y <= iHeight; Y += this.CellHeight)
{
g.DrawLine(myPen, 0, Y, iWidth, Y);
}
}
}
public override void Refresh()
{
base.ResumeLayout(true);
base.Refresh();
ResumeLayout(true);
}
}
Form Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnBrowse_Click(object sender, EventArgs e)
{
try
{
if (ofdImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pbImage.Image = Image.FromFile(ofdImage.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnShowGrid_Click(object sender, EventArgs e)
{
if (grid1.Visible)
{
grid1.Visible = false;
btnShowGrid.Text = "Show";
}
else
{
grid1.Visible = true;
btnShowGrid.Text = "Hide";
}
}
private void btnGridCellMaximize_Click(object sender, EventArgs e)
{
grid1.CellHeight += 1;
grid1.CellWidth += 1;
grid1.Refresh();
}
private void btnGridCellMinimize_Click(object sender, EventArgs e)
{
grid1.CellHeight -= 1;
grid1.CellWidth -= 1;
grid1.Refresh();
}
}