【发布时间】:2018-10-08 14:42:50
【问题描述】:
我有一个显示数据的datagridview,但显示的数据并没有填满datagridview 的灰色背景显示的整个datagridview。我想要发生的是显示 datagridview 的网格线,即使每行中没有数据。
幸运的是,我找到了一个与此相关的代码(此代码用于 AutoSizeColumnsMode 属性 == Fill,但我需要将此属性设置为 AllCells,以便在每列中使用更长的字符串) 起初我以为这是我要找的代码:
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
int rowHeight = this.dataGridView1.RowTemplate.Height;
Pen slategraypen = new Pen(Brushes.SlateGray,0.5f);
slategraypen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;
slategraypen.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
int h = this.dataGridView1.ColumnHeadersHeight + (rowHeight) * (this.dataGridView1.NewRowIndex);
Bitmap rowImg = new Bitmap(this.dataGridView1.Width, rowHeight);
Graphics g = Graphics.FromImage(rowImg);
Rectangle rFrame = new Rectangle(1, 1, this.dataGridView1.Width-4, rowHeight);
g.DrawRectangle(slategraypen, rFrame);
Rectangle rFill = new Rectangle(2, 1, this.dataGridView1.Width - 4, rowHeight-1);
g.FillRectangle(Brushes.White, rFill);
// for rowheaders drawing. in my case, I dont want to show the rowheaders so I didnt include this in my code
//Rectangle rowHeader = new Rectangle(2, 2, this.dataGridView1.RowHeadersWidth - 2, rowHeight - 4);
//g.FillRectangle(new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.BackColor), rowHeader);
int w = this.dataGridView1.RowHeadersWidth-40;// -40 is the width of the row header that I dont want to show
for (int j = 0; j < this.dataGridView1.ColumnCount; j++)
{
w += this.dataGridView1.Columns[j].Width;
g.DrawLine(slategraypen, new Point(w, 0), new Point(w, rowHeight));
}
int loop = (this.dataGridView1.Height - h) / rowHeight;
for (int j = 0; j < loop + 1; j++)
{
e.Graphics.DrawImage(rowImg, 0, h + j * rowHeight);
}
}
这发生了:
但是,当我在列中输入一个长字符串时,会发生这种情况: 请注意 datagridview 的右侧部分,由于为 autosizecolumnsmode 设置的填充属性,某些列会缩小
我尝试将 AutoSizeColumnsMode 属性更改为 allcells 并且发生了这种情况: 每当我滚动水平滚动条时,下面绘制的线条都被绘制在错误的位置。我不太确定如果我上下滚动垂直滚动条是否也会发生这种情况。
我需要您的帮助来编写正确的代码。非常感谢您的帮助。
【问题讨论】:
-
你为什么要这个?在没有单元格的地方绘制单元格会诱使用户点击那里,不是吗?如果您想要行,请添加更多行!
-
我只是不想显示第一张图片上的灰色部分。看到那个灰色的部分对我来说看起来不太好。在网上寻找答案时,我在 social.msdn.mircosoft.com 上找到了上面的代码。
-
您始终可以将背景颜色更改为白色。当然,如果考虑到滚动,它可以正确编码,但 imo 它仍然具有误导性。
-
哦,是的,我尝试将其更改为白色,但看起来也不好看。我希望我的 datagridview 看起来像一个 excel 表 :) 你能帮我吗?
-
它是只读的还是禁用的??如果它看起来像一个 Excel 表格,但实际上已经死了,用户会讨厌..
标签: c# datagridview show gridlines