C# Change background color of a table cell inTableLayoutPanel

后端 未结 2 1655
野的像风
野的像风 2021-01-22 01:54

I am trying to change the background color of a table cell inside a TableLayoutPanel programmatically. The cells can either be null or taken by a user

2条回答
  •  无人及你
    2021-01-22 02:37

    Note that there really is no such thing a TableLayoutPanelCell. The 'cells' are strictly virtual.

    You can use the CellPaint event to draw any BackColor onto any 'cell', empty or not:

    private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
    
        if (e.Row == e.Column)
            using (SolidBrush brush = new SolidBrush(Color.AliceBlue))
                e.Graphics.FillRectangle(brush, e.CellBounds);
        else
            using (SolidBrush brush = new SolidBrush(Color.FromArgb(123, 234, 0)))
                e.Graphics.FillRectangle(brush, e.CellBounds);
    }
    

    Of course the colors and the conditions are up to you..

    Update: Note once more that you cannot color a certain 'cell' because there are no TableLayoutPanelCells! No such class, neither controls nor even objects. It just doesn't exist! A TLP is not made up of 'cells'. It is made up of rows and columns only.

    So to color a 'cell' you need to code a suitable condition in the CellPaint event, which is the closest .NET comes to using the name 'cell'.

    You can use simple formulas or explicit enumerations to create the color layout you want, depending on you needs.

    Here are two more elaborate examples:

    For a simple checkerboard layout use this condition:

    if ((e.Row + e.Column) % 2 == 0)
    

    For a freeform layout collect all color values in a Dictionary, Color ;

    Dictionary cellcolors = new Dictionary();
    cellcolors.Add(new Point(0, 1), Color.CadetBlue);
    cellcolors.Add(new Point(2, 4), Color.Blue);
    ..
    ..
    ..
    

    and write:

    private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        if (cellcolors.Keys.Contains(new Point(e.Column, e.Row )))
            using (SolidBrush brush = new SolidBrush(cellcolors[new Point(e.Column, e.Row )]))
                e.Graphics.FillRectangle(brush, e.CellBounds);
        else
            using (SolidBrush brush = new SolidBrush(defaultColor))
                e.Graphics.FillRectangle(brush, e.CellBounds);
    }
    

提交回复
热议问题