更改DataGridView单元格中按钮的颜色

我有一个大的DataGridView控件,它有几个单元格,其中大部分都包含一个按钮。 如何更改这些按钮的颜色?

这会更改按钮的“轮廓”,但不会更改按钮本身。

row.Cells[2].Style.BackColor = System.Drawing.Color.Red; 

这似乎没有改变任何可见的东西:

 row.Cells[2].Style.ForeColor = System.Drawing.Color.Red; 

如果无法更改背景,是否可以更改按钮上的字体?

使用.NET 2.0。

根据MSDN:

启用视觉样式时,按钮列中的按钮使用ButtonRenderer绘制,而通过DefaultCellStyle等属性指定的单元格样式不起作用。

因此,您有两种选择之一。 在Program.cs中,您可以删除此行:

 Application.EnableVisualStyles(); 

这将使它工作,但让其他一切看起来像垃圾。 你的另一个选择,你不会喜欢这个,是从DataGridViewButtonCellinheritance并覆盖Paint()方法。 然后,您可以在名为DrawButtonButtonRenderer类上使用静态方法,自己绘制按钮。 这意味着要弄清楚细胞当前处于哪种状态(点击,hover等)并绘制角落和边界等等……你明白了,这是可行的,但却是巨大的痛苦。

如果您愿意,这里只是一些示例代码来帮助您入门:

  //Custom ButtonCell public class MyButtonCell : DataGridViewButtonCell { protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { ButtonRenderer.DrawButton(graphics, cellBounds, formattedValue.ToString(), new Font("Comic Sans MS", 9.0f, FontStyle.Bold), true, System.Windows.Forms.VisualStyles.PushButtonState.Default); } } 

然后这是一个测试DataGridView:

 DataGridViewButtonColumn c = new DataGridViewButtonColumn(); c.CellTemplate = new MyButtonColumn(); this.dataGridView1.Columns.Add(c); this.dataGridView1.Rows.Add("Click Me"); 

所有这些示例都是,绘制一个字体为“Comic Sans MS”的按钮。 它不会考虑您在运行应用程序时看到的按钮状态。

祝好运!!

我错过了Dave关于Tomas回答的说明,所以我只是发布了简单的解决方案。

将Button列的FlatStyle属性更新为Popup,然后通过更新背景颜色和forecolor,您可以更改按钮的外观。

 DataGridViewButtonColumn c = (DataGridViewButtonColumn)myGrid.Columns["colFollowUp"]; c.FlatStyle = FlatStyle.Popup; c.DefaultCellStyle.ForeColor = Color.Navy; c.DefaultCellStyle.BackColor = Color.Yellow; 

如果这些单元格包含一个按钮,我很确定你必须访问该按钮的属性BackColor。 IE浏览器。 获取单元格的值将其转换为按钮并设置其属性。

使用ButtonRenderer绘制DataGridView中的默认按钮,这使得覆盖非常困难。 如果我是你,我只需将FlatStyle按钮设置为“Popup”。

 DataGridViewButtonCell buttonCell = (DataGridViewButtonCell)dataGridMappings.Rows[0].Cells[0]; buttonCell.FlatStyle = FlatStyle.Popup; buttonCell.Style.BackColor = System.Drawing.Color.Red; 

我认为你错了:

 row.Cells[2].Style.BackColor = System.Drawing.Color.Red; 

你说更新按钮的“轮廓”,但它确实更新了按钮后面的单元格。

像这样的东西应该工作:

 row.Cells[2].ButtonName.Style.BackColor = System.Drawing.Color.Red; 

使用自定义Paint方法从DataGridViewButtonCell派生自己的类是绝对足够的,而无需删除EnableVisualStyles()