【发布时间】:2011-03-11 20:12:35
【问题描述】:
如何在 C# windows 应用程序中更改 datagridview 选定行的背景颜色?
【问题讨论】:
-
您需要为问题添加更多细节,也许发布一些代码以及您尝试过的内容以及失败的内容。您的问题目前无法回答。
标签: c# winforms datagridview
如何在 C# windows 应用程序中更改 datagridview 选定行的背景颜色?
【问题讨论】:
标签: c# winforms datagridview
拜托,必须有一个简单的解决方案,终于找到了。
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red;
这对我有用,没有复杂的代码,没有事件处理。我以前做过,但不记得了,所以认为发布它会帮助其他人和我将来:)
【讨论】:
DataGridView 上有一个DefaultCellStyle,里面有SelectionBackColor 和SelectionForeColor 属性。
DataGridView 采用了样式继承的思想,以防你发现你选择的样式没有被应用:
【讨论】:
利用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_SelectionChanged(object sender, EventArgs e)
{
(sender as DataGridView).CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
}
【讨论】:
这是我的代码
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}
【讨论】: