在 WinForm C# 中单击按钮时更改表格单元格颜色 [英] Change table cell color when a button is clicked in WinForm C#
问题描述
我对 Windows 窗体非常陌生,已经搜索了三天的答案,但没有成功.
I am very new to Windows Forms, have been searching for an answer for three days already but no luck.
我有一个按钮和一个包含多个单元格的表格.
I have a button and a table with multiple cells.
当按钮被点击时,我需要改变左上角单元格的颜色(索引 [0, 0]),但我不明白如何去做,因为 按钮的点击事件方法没有 TableLayoutCellPaintEventArgs 元素类型参数.
When the button is clicked, I need to change the color of the top left cell (index [0, 0]), but I don't understand how to do it since the button's on-click event method doesn't have TableLayoutCellPaintEventArgs element type parameter.
请告知如何操作.
推荐答案
感谢 Jackdaw 的回答,我找到了适合我的解决方案:
Thanks to Jackdaw's answer I was able to figure our a solution that worked for me:
我正在 tableLayoutPanel1_CellPaint 事件处理程序中更改表格单元格的颜色,然后使用此脚本从按钮的事件处理程序中调用它:
I am changing colors of the table cells in tableLayoutPanel1_CellPaint event handler, and then calling it from the button's event handler using this script:
this.tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
this.tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
我错过了 tableLayoutPanel1.Refresh();部分,但在寒鸦的回答之后,我注意到并能够添加它.现在一切正常.
I was missing tableLayoutPanel1.Refresh(); part, but after Jackdaw's answer I noticed and was able to add it. Everything is working correctly now.
完整的脚本如下所示:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 0 && e.Column == 2)
e.Graphics.FillRectangle(Brushes.Red, e.CellBounds);
}
private void button1_Click(object sender, EventArgs e)
{
this.tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
tableLayoutPanel1.Refresh();
}
感谢您的帮助!
这篇关于在 WinForm C# 中单击按钮时更改表格单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!