C# 如何在自定义控件中绘制宽度相同的列

C# 如何在自定义控件中绘制宽度相同的列,c#,user-controls,system.drawing,C#,User Controls,System.drawing,我正在制作一个自定义网格控件,我需要绘制具有相同宽度的列。但最后一列的宽度约为1px,如图所示 我认为代码很好,但没有按预期工作 你能帮我一下吗 已解决 问题是控制内部利润。当您将BorderStyle属性设置为表示可以看到任何边框的任何值时,控件将缩小一些像素 代码如下: public partial class CustomGrid : Panel { // number of columns to draw private int hrows; privat

我正在制作一个自定义网格控件,我需要绘制具有相同宽度的列。但最后一列的宽度约为1px,如图所示

我认为代码很好,但没有按预期工作

你能帮我一下吗

已解决

问题是控制内部利润。当您将BorderStyle属性设置为表示可以看到任何边框的任何值时,控件将缩小一些像素

代码如下:

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;
            }

        }


    }

}
公共部分类CustomGrid:面板
{
//要绘制的列数
私人住宅;
私有布尔网格;
//单元格宽度
私人浮动单元格宽度;
私有宽度;
私家车高度;
public void EnableGrid()
{
//ClientRect与控件大小不匹配,因此我使用了Control.Width
this.rectwidth=this.Width;
this.rectheight=this.Height;
//计算单元尺寸
this.cellwidth=(float)this.rectwidth/this.hrows;
this.drawgrid=true;
这个。使无效();
}
受保护的覆盖无效OnPaint(PaintEventArgs e)
{
if(此.drawgrid)
{
浮动电流=此宽度;
//画栏
while(当前<此宽度)
{
e、 拉丝
(
钢笔,黑色,
电流,//x1
0f,//y1
当前值,//x2
此参数的高度为//y2
);
电流+=此.cellwidth;
}
}
}
}

这是一个基本的数学问题,如果ClientSize.Width控件正好可以被列数整除,则只能得到大小完全相同的列。这只是偶然发生的。当用户将控件拖放到窗体上时,您必须调整所选的宽度,方法是故意将网格画得更小,从而使列的宽度完全相等。或者通过在列之间分配可用空间,最终使某些列缩小一个像素。