Draw vertical bold lines between some columns in datagridview

  • Thread starter Thread starter Henry Vuong
  • Start date Start date
H

Henry Vuong

Guest
I want to draw vertical bold red lines between some columns in a datagridview. I created a form and a datagridview, and this is what I want to get:

1448478.jpg

But this is what I get, notice the two vertical red lines in column header:

1448480.jpg

Here's my code:


private void Form1_Load(object sender, EventArgs e)
{

this.dataGridView1.Columns.Add("Col_A", "Column A");
this.dataGridView1.Columns.Add("Col_B", "Column B");
this.dataGridView1.Columns.Add("Col_C", "Column C");
this.dataGridView1.Columns.Add("Col_D", "Column D");
this.dataGridView1.Columns.Add("Col_E", "Column E");
this.dataGridView1.Columns.Add("Col_F", "Column F");

//Add rows to datagridview
for (int i = 0; i < 50; i++)
{
this.dataGridView1.Rows.Add("A" + i.ToString(), "B" + i.ToString(), "C" + i.ToString(),
"D" + i.ToString(), "E" + i.ToString(), "F" + i.ToString());
}

//Set the width of columns
for (int j = 0; j < this.dataGridView1.ColumnCount; j++)
{
this.dataGridView1.Columns[j].Width = 90;
}

this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
}

//Cell painting event
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//Using red pen to draw border
using (var redPen = new Pen(Color.Red, 3))
{
//Get the x coordination value of the left line
int left_x = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns["Col_B"].Index, this.dataGridView1.Rows[0].Index, true).X;

//Get the x coordination value of the right line
int right_x = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns["Col_D"].Index, this.dataGridView1.Rows[0].Index, true).X
+ this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns["Col_D"].Index,this.dataGridView1.Rows[0].Index, true).Width;

//Get the y coordination value of the top of each line
int top_y = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns[0].Index, this.dataGridView1.Rows[0].Index, true).Y;

//Get the y coordination value of the bottom of each line
int bottom_y = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns[0].Index, this.dataGridView1.Rows[dataGridView1.Rows.Count - 1].Index, true).Y
+ this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns[0].Index, this.dataGridView1.Rows[dataGridView1.Rows.Count - 1].Index, true).Height;

//Draw the lines using red pen and the x, y values above
e.Graphics.DrawLine(redPen, new Point(left_x, top_y), new Point(left_x, bottom_y));
e.Graphics.DrawLine(redPen, new Point(right_x, top_y), new Point(right_x, bottom_y));
}
}


If I reduce the number of rows to just a few so that all the rows will appear in the form what it first appears, then the red lines appear just as I wanted. But when some rows are hidden, it's screwed up. What am I missing?

Thanks.

Continue reading...
 
Back
Top