I have a datagridview that displays data but the data displayed doesn't fill the whole datagridview that the gray background of datagridview shows. what I want to happen is to show gridlines of the datagridview even with out data in each rows.
luckily, I found a code regarding this, (this code is for AutoSizeColumnsMode property == Fill but I need this property to be set to AllCells for longer strings inside each columns) at first I thought that this is the code im looking for:
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);
}
}
and this happened:
But, when I enter a long string in a column this happens:
notice the right part of the datagridview, some columns shrink because of the fill property set for autosizecolumnsmode
I tried to change AutoSizeColumnsMode property to allcells and this happened: whenever I scroll the horizontal scrollbar, the lines drawn below were being draw on the wrong places. im not quite sure if this will also happen if I scroll a vertical scrollbar up and down.
I need your help in writing the correct code for this. I would really appreciate your help.