DataGridView是Windows Forms中的一个强大控件,用于显示和编辑表格数据。默认情况下,选中的行会以系统默认的高亮颜色显示,但开发者可以自定义这个外观。
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Selected)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightBlue;
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.SelectionBackColor = Color.LightBlue;
}
else
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
}
}
// 设置选中行的背景色
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightGreen;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
// 如果需要为特定列设置不同的颜色
dataGridView1.Columns["ColumnName"].DefaultCellStyle.SelectionBackColor = Color.Orange;
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Selected)
{
e.CellStyle.BackColor = Color.LightGoldenrodYellow;
e.CellStyle.ForeColor = Color.Black;
}
}
SystemColors.Highlight
。// 在Form_Load或初始化代码中
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightCoral;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
// 如果需要根据条件动态改变颜色
dataGridView1.CellFormatting += (sender, e) =>
{
var grid = sender as DataGridView;
if (grid.Rows[e.RowIndex].Selected)
{
e.CellStyle.BackColor = Color.LightSkyBlue;
e.CellStyle.ForeColor = Color.DarkBlue;
}
};
通过以上方法,您可以灵活地控制DataGridView中选中行的外观,满足不同的UI设计需求。