效果直接在DataGridView的属性中可以设置,选中记录时的模式是选择整行即可。
要求是选中的行变色,代码如下
事件是RowPrePaint。
这个思路是先得到当前的行。RowPrePaint事件应该是每Paint一行之前的事件,所以对行进行检查,如果满足要求就设置成想要的样式即可。因为要把非当前行还原样式,所以记录了之前的颜色,估计直接记录Style也是一种好方法。
- void DataGridView1RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
- {
- if (e.RowIndex >= dataGridView1.Rows.Count - 1)
- return;
- var row = (sender as DataGridView).Rows[e.RowIndex];
- try
- {
- Color oldForeColor = new Color();
- Color oldBackColor = new Color();
- if (row == (sender as DataGridView).CurrentRow) {
- if(row.DefaultCellStyle.ForeColor != Color.White)
- {
- oldForeColor = row.DefaultCellStyle.ForeColor;
- row.DefaultCellStyle.ForeColor = Color.White;
- }
- if(row.DefaultCellStyle.BackColor != Color.Blue)
- {
- oldBackColor = row.DefaultCellStyle.BackColor;
- row.DefaultCellStyle.BackColor = Color.Blue;
- }
- }
- else
- {
- row.DefaultCellStyle.ForeColor = oldForeColor;
- row.DefaultCellStyle.BackColor = oldBackColor;
- }
- }
- catch (Exception)
- {
- }
- }