如何更改datagridview选定行的背景颜色?

35

在 C# 的 Windows 应用程序中,如何更改 datagridview 选定行的背景颜色?


你需要添加更多细节到问题中,可能发布一些代码以及你尝试过什么以及失败了什么。你目前的问题无法回答。 - Oded
6个回答

55

加油啊... 这一定有一个简单的解决方案,最终找到了一个。

dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red;

这对我有用,没有复杂的代码,也没有事件处理。我以前做过,但是想不起来了,所以觉得发布它会帮助其他人和我自己。


34

在 DataGridView 控件中有一个名为 DefaultCellStyle 的属性,其中包含 SelectionBackColorSelectionForeColor 属性。

DataGridView 使用样式继承的概念。如果您发现所选择的样式未被应用,请参考以下链接:

http://msdn.microsoft.com/en-us/library/1yef90x0.aspx


4

以下是简单且可直接复制粘贴的版本:

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    (sender as DataGridView).CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
}

这正是我所寻找的,谢谢! - Freddy

3
利用 DataGridViewCell 的事件 CellEnterCellLeave,您可以尝试以下操作:
private void foobarDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  DataGridViewCellStyle fooCellStyle = new DataGridViewCellStyle();
  fooCellStyle.BackColor = System.Drawing.Color.LightYellow;
  this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(fooCellStyle);
}

private void foobarFinderDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
{
  DataGridViewCellStyle barCellStyle = new DataGridViewCellStyle();
  barCellStyle.BackColor = System.Drawing.Color.White;
  this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(barCellStyle);
}

如果选中之前的行颜色不是白色会怎么样? - Thunder
我的意思只是举了一个快速示例来说明这个概念 - 你只需要创建一个帮助方法来检索你需要切换的任何颜色。 - Nano Taboada

3

在“DataGridView”的设计器中也可以更改颜色。

enter image description here


2
这是我的代码。
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}

太棒了,Adam!我从来不知道那个存在!! - user7075507

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