How to apply border color for TableLayoutPanel

May 02, 2013 by Anuraj

.Net .Net 4.0 Windows Forms

The TableLayoutPanel control arranges its contents in a grid. TableLayoutPanel doesn’t have border color property, but you can write custom code in CellPaint event to create border. Here is the code snippet which will help you to create border and apply color for TableLayoutPanel

var panel = sender as TableLayoutPanel;
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
var rectangle = e.CellBounds;
using (var pen = new Pen(Color.Black, 1))
{
    pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
    pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
    
    if (e.Row == (panel.RowCount - 1))
    {
        rectangle.Height -= 1;
    }

    if (e.Column == (panel.ColumnCount - 1))
    {
        rectangle.Width -= 1;
    }

    e.Graphics.DrawRectangle(pen, rectangle);
}

Here is the screen shot of the Form in Design Time

Form in Design Time

And in Runtime

Form in Runtime

Happy Coding

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub