在 C# 的 Windows 应用程序中,如何更改 datagridview 选定行的背景颜色?
在 C# 的 Windows 应用程序中,如何更改 datagridview 选定行的背景颜色?
加油啊... 这一定有一个简单的解决方案,最终找到了一个。
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red;
这对我有用,没有复杂的代码,也没有事件处理。我以前做过,但是想不起来了,所以觉得发布它会帮助其他人和我自己。
在 DataGridView 控件中有一个名为 DefaultCellStyle
的属性,其中包含 SelectionBackColor
和 SelectionForeColor
属性。
DataGridView 使用样式继承的概念。如果您发现所选择的样式未被应用,请参考以下链接:
以下是简单且可直接复制粘贴的版本:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
(sender as DataGridView).CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
}
DataGridViewCell
的事件 CellEnter
和 CellLeave
,您可以尝试以下操作: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);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}