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:
But this is what I get, notice the two vertical red lines in column header:
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");
-
-
- 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());
- }
-
-
- for (int j = 0; j < this.dataGridView1.ColumnCount; j++)
- {
- this.dataGridView1.Columns[j].Width = 90;
- }
-
- this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
- }
-
-
- void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
- {
-
- using (var redPen = new Pen(Color.Red, 3))
- {
-
- int left_x = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns["Col_B"].Index, this.dataGridView1.Rows[0].Index, true).X;
-
-
- 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;
-
-
- int top_y = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns[0].Index, this.dataGridView1.Rows[0].Index, true).Y;
-
-
- 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;
-
-
- 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.