如何在DataGridView中更改列的颜色?

20

我有一个DataGridview,并且为了数据输入目的,将其中一些列设为只读。当我这样做时,该列仍然保持正常白色(虽然不允许输入)。如何将该列变为灰色?我看到很多关于如何对行进行着色的示例,但没有涉及列。

如何使只读列呈现灰色外观?

4个回答

36

尝试为所选列设置 DefaultCellStyle 属性。

编辑:

grid.Columns["NameOfColumn"].DefaultCellStyle.ForeColor = Color.Gray;

2
ForeColor 改变文本颜色。BackColor 改变背景颜色。 - Scott Uphus

13

只需更改DataGridViewColumn对象的样式即可。

myGrid.Columns["myColumn"].DefaultCellStyle.BackColor = Color.Red;

1
我给你点赞是因为你改对了(尤其是使用列名而不是索引,我讨厌使用索引),但我想要灰色...而不是红色。 :-) - MAW74656
1
它是Color.Red而不是Colors.Red。 - Narayan

5
您可以使用DataGridViewColumn的 DefaultCellStyle属性来指定列的单元格背景颜色。
DataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Gray;

1
        DataGridViewColumn firstColumn = dataGridView.Columns[0];
        DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
        cellStyle.BackColor = Color.Grey;

        firstColumn.DefaultCellStyle = cellStyle;

我看到这个方案可以行得通,但是需要比其他解决方案更多的代码。 - MAW74656

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接