-->

C# Change background color of a table cell inTable

2020-04-16 03:32发布

问题:

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 control during runtime (always changing).

I was doing this:

TableName.GetControlFromPosition(column, row).BackColor = Color.CornflowerBlue;

Of course, this only works if there is something at that cell. How can I also change the properties of a null cell at runtime?

回答1:

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<Point>, Color ;

Dictionary<Point, Color> cellcolors = new Dictionary<Point, Color>();
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);
}


回答2:

when the cell is null, you can not set it's BackColor property. When set color, you should check if it is null. And you can set color of controls in the cells rather than cell's BackColor. example