我需要编写一个函数,该函数将TableLayoutPanel
在运行程序期间根据某些条件设置单元格中的颜色。
TableLayoutPanel
除以16x16。程序启动时存在一些条件。如果该条件对于某个单元格为真,则此销售必须涂成蓝色。例如:
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?)
}
}
}
我发现了这样的例子:
private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 0 && e.Column == 1)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);
}
}
但是我不知道如何使用它。如果有人知道这一点,请帮助我。
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
}
}
}
}
这是一个分步示例:
Form
TableLayoutPanel
来自工具箱放到您的Form
tableLayoutPanel1
在设计图面上选择,然后F4按键以查看属性。CellPaint
事件以tableLayoutPanel1_CellPaint
在代码中创建事件处理程序。e.Row
它是行索引,e.Column
列索引和e.CellBounds
绘画单元格的边界。例如在下面的示例中,我们绘制黑色背景,if ((e.Column + e.Row) % 2 == 1)
否则,我们绘制白色背景:
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);
}
动态更改颜色
要从程序的另一点更改颜色,例如在Click
发生按钮事件时,应将每个单元格的颜色存储在二维数组中,并使用该颜色为该单元格创建画笔:
bgColors
在您的表单中定义:
Color[,] bgColors = new Color[2, 2] {
{ SystemColors.Control, SystemColors.Control },
{ SystemColors.Control, SystemColors.Control }
};
通过以下方式绘制单元格的背景:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
using (var b = new SolidBrush(bgColors[e.Column, e.Row]))
{
e.Graphics.FillRectangle(b , e.CellBounds);
}
}
要更改BackColor
,Cell
您可以:
private void Button1_Click(object sender, EventArgs e)
{
//column: 0 ,row: 1
bgColors[0, 1] = Color.Red;
tableLayoutPanel1.Refresh();
}
作为另一个简单的选项,您可以放入Panel
每个单元格,将的Dock
属性设置Panel
为Fill
,将其Margin
属性设置为0,0
,然后每次要在位置更改面板的颜色时,(column, row)
都可以使用以下代码:
this.tableLayoutPanel1.GetControlFromPosition(column, row).BackColor = Color.Red;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句