I need to write a function which will set the color in TableLayoutPanel
cells depending on some condition during running the program.
TableLayoutPanel
is divided by 16x16. There is some condition at the start of the program. If the condition is true for a cell this sell must be painted blue color. For example:
private void start_Click(object sender, EventArgs e)
{
foreach (string str in some_list)
{
if (some condition)
{
set_color_in_cell at row[i] colum[j] //(what shoud i use here?)
}
}
}
I found such example:
private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 0 && e.Column == 1)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);
}
}
But I don't understand how to use it. If somebody knows about this please help me.
private void start_Click(object sender, EventArgs e)
{
string SyncAnswer = "";
foreach (string file_string in Data_from_file)
{
COM_Port.WriteLine(file_string);
while (SyncAnswer != "READY")
{
SyncAnswer = COM_Port.ReadLine();
if (SyncAnswer.Substring(0, 4) == "Fire")
{
//raise event
//paint for example a cell in Row=i Colum=j
}
else if (SyncAnswer.Substring(0, 4) == "Skip")
{
//raise event
}
}
}
}
Option 1 - Using CellPaint Event
Here is a step by step example:
Form
TableLayoutPanel
from toolbox on yourForm
tableLayoutPanel1
on design surface and Press F4 Key to see properties.CellPaint
event to createtableLayoutPanel1_CellPaint
event handler in code.e.Row
is the row index,e.Column
is column index ande.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: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:Draw background of cells this way:
To change the
BackColor
of aCell
you can:Option 2 - Hosting Panel in Cells
As another simple option, you can put
Panel
in each cell, and set theDock
property ofPanel
toFill
and set itsMargin
property to0,0
, then each time you want to change color of a panel at position(column, row)
you can use this code: