Share via

Change border of datagridview

OmkarHcl 206 Reputation points
2023-06-02T13:36:36.62+00:00

I am trying to Change the border style of datagridview's header to like below image but i dont find any reference for that . the above border should be thick while the bottom border is thin . Also there should be no side borders . Is it possible to create that datagridview ? Please suggest the code for this .

datagridview header

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Hui Liu-MSFT 48,711 Reputation points Microsoft External Staff
2023-06-08T02:35:45.6366667+00:00

Hi,@OmkarHcl. You can subscribe to the CellPainting event of the DataGridView control and specify the dataGridView1_CellPainting method as the event handler.

I set the color of the pen that draws the header to red in order to see the effect more clearly.

using (Pen topBorderPen = new Pen(Color.Red, 2f)) using (Pen bottomBorderPen = new Pen(Color.Red, 1f))

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex >= 0) 
            {
               // e.PaintBackground(e.CellBounds, true);
                using (Brush headerBrush = new SolidBrush(Color.LightSalmon))
                {
                    e.Graphics.FillRectangle(headerBrush, e.CellBounds);
                }
                using (Pen topBorderPen = new Pen(Color.Red, 2f))
                using (Pen bottomBorderPen = new Pen(Color.Red, 1f))
                {
                    e.Graphics.DrawLine(topBorderPen, e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Right, e.CellBounds.Top);

                    e.Graphics.DrawLine(bottomBorderPen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
                }

                TextRenderer.DrawText(e.Graphics, e.Value.ToString(), e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);

                e.Handled = true;
            }
        }

The result:

User's image


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.