我正在制作自定义网格控件,我需要绘制宽度相同的列。但是最后一列大约是1px窄,如图所示。
我认为代码很好,但是没有按预期工作。
你能帮我一把吗?
解决
问题是控制内部利润。当您将BorderStyle属性设置为任何值,这意味着可以看到任何边框,控件的某些像素更窄。
example-form http://i58.tinypic.com/2h30g1t.jpg
以下是代码:
public partial class CustomGrid : Panel
{
// number of columns to draw
private int hrows;
private bool drawgrid;
// cell width
private float cellwidth;
private int rectwidth;
private int rectheight;
public void EnableGrid()
{
// ClientRect does not match with Control Size, so I used Control.Width
this.rectwidth = this.Width;
this.rectheight = this.Height;
// compute cell dimension
this.cellwidth = (float)this.rectwidth / this.hrows;
this.drawgrid = true;
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
if (this.drawgrid)
{
float current = this.cellwidth;
// draw columns
while (current < this.rectwidth)
{
e.Graphics.DrawLine
(
Pens.Black,
current, //x1
0f, //y1
current, //x2
this.rectheight //y2
);
current += this.cellwidth;
}
}
}
}