How to set cell color in TableLayoutPanel dynamically?

时间秒杀一切 提交于 2019-12-01 18:05:50

Option 1 - Using CellPaint Event

Here is a step by step example:

  1. Create a Form
  2. Put a TableLayoutPanel from toolbox on your Form
  3. Select tableLayoutPanel1 on design surface and Press F4 Key to see properties.
  4. From toolbar of property grid, you can select to show Properties

    or Events

    . Click on events icon and from the list, double click on CellPaint event to create tableLayoutPanel1_CellPaint event handler in code.
  5. You can paint each cells background in this method based on some criteria. The event will raise for painting each cells background and e.Row is the row index, e.Column is column index and e.CellBounds is bound of the painting cell.

For example in below sample, we draw black background if ((e.Column + e.Row) % 2 == 1) otherwise, we draw white background:

private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
    if ((e.Column + e.Row) % 2 == 1)
        e.Graphics.FillRectangle(Brushes.Black, e.CellBounds);
    else
        e.Graphics.FillRectangle(Brushes.White, e.CellBounds);
}

To change Color Dynamically

To change the color from another point of program, for example in a Click event of a button, you should store back colors of each cell in an 2-dimension array and use that color to create a brush for that cell:

Define bgColors in your form:

Color[,] bgColors = new Color[2, 2] {
    { SystemColors.Control, SystemColors.Control }, 
    { SystemColors.Control, SystemColors.Control } 
};

Draw background of cells this way:

private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
    using (var b = new SolidBrush(bgColors[e.Column, e.Row]))
    {
        e.Graphics.FillRectangle(b , e.CellBounds);
    }
}

To change the BackColor of a Cell you can:

private void Button1_Click(object sender, EventArgs e)
{
    //column: 0 ,row: 1
    bgColors[0, 1] = Color.Red;
    tableLayoutPanel1.Refresh();
}

Option 2 - Hosting Panel in Cells

As another simple option, you can put Panel in each cell, and set the Dock property of Panel to Fill and set its Margin property to 0,0, then each time you want to change color of a panel at position (column, row) you can use this code:

this.tableLayoutPanel1.GetControlFromPosition(column, row).BackColor = Color.Red;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!