2016-08-03 1410 views
1

我试图以编程方式更改TableLayoutPanel内部表格单元格的背景色。单元格可以是null,也可以是运行时用户控件(始终更改)。C#更改TableLayoutPanel中表格单元格的背景颜色

我这样做:

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

当然,如果在该单元格的东西这仅适用。我怎样才能在运行时更改空单元的属性?

回答

1

请注意,确实没有这样的东西TableLayoutPanelCell。 '细胞'严格为虚拟

可以使用CellPaint事件得出任何BackColor到任何“细胞”,为空或不:

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); 
} 

enter image description here

当然颜色和条件是由你..

更新:请再次注意,您无法为某个“单元格”着色,因为TableLayoutPanelCells!没有这样的班级,既不控制也不控制对象。它只是不存在! TLP是由'细胞'组成的而不是。它仅由行和列组成。

所以要给“单元格”着色,您需要在CellPaint事件中编写合适的条件,这是最接近于使用名称“单元格”的.NET。

根据您的需要,您可以使用简单的公式或显式枚举来创建所需的颜色布局。

这里有两个更详细的例子:

对于一个简单的棋盘布局使用此条件:

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

对于自由布局收集在一个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); 
.. 
.. 
.. 

写:

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); 
} 
+0

如何指定使用此事件着色哪个单元格? 'TableLayoutCellPaintEvenArgs'只有'get'用于'Row'和'Column',所以我不能设置这些值。我有一个二维数组,表示填充1和0(总是变化)的表格。我想为单元格中存在“1”的单元格着色。现在,无论条件如何,该事件都在绘制整张桌子。 –

+1

为每个“单元格”和每次刷新调用此事件。因此,要设置某些单元格的颜色,您需要在条件中对其行/列索引进行编码。根据您的需要,这可以像一个公式一样简单,或者像列举每个单元格一样繁琐。看看我的更新了两个更多的例子! - 你写道:_现在,事件正在绘制整张桌子,不管情况如何。这肯定是不正确的,或者说:是的,所有'单元格'总是使用这个事件来绘制,但__always根据你写的条件___。 – TaW

+0

非常感谢!现在一切都说得通了。 –

1

当单元格为空时,您无法设置它的BackColor属性。设置颜色时,应检查它是否为空。你可以在单元格中设置控件的颜色,而不是单元格的BackColor。 example

+0

你对我应该怎么做,然后一个建议?我有64个单元格。我正在考虑制作64块面板,并在每个单元中放置一块。然后将用户控件放在每个面板中。你怎么看? –

+1

是的,当然你可以得到你想要的,就像你说的那样。 我照你说的做了。 \t'private void Form1_Load(object sender,EventArgs e) { panel1.BackColor = Color。绿色; panel2.BackColor = Color.Red; panel5.BackColor = Color.Yellow; panel7.BackColor = Color.SeaGreen; }' 你可以设置任何面板的BackColor。 – Gry

相关问题