Jim*_*her 11 datagridview row selection winforms
我有一个DataGridView,其中每行的背景根据数据绑定项而不同.但是,当我选择一行时,我再也看不到它的原始背景颜色了.
为了解决这个问题,我想到了两个解决方案:
我可以将选择设置为半透明,从而可以查看两个选定的行是否具有不同的背景颜色.
要么; 我可以完全删除选择颜色,并在选定的行周围绘制边框.
什么选项更容易,我该怎么做?
这是一个WinForm应用程序.
编辑:我最终使用了一些代码,adrift
private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (dgv.Rows[e.RowIndex].Selected)
{
var row = dgv.Rows[e.RowIndex];
var bgColor = row.DefaultCellStyle.BackColor;
row.DefaultCellStyle.SelectionBackColor = Color.FromArgb(bgColor.R * 5 / 6, bgColor.G * 5 / 6, bgColor.B * 5 / 6);
}
}
Run Code Online (Sandbox Code Playgroud)
这给人一种半透明选择颜色的印象.谢谢你的帮助!
如果要在选定行周围绘制边框,可以使用DataGridView.RowPostPaintEvent,并"清除"选择颜色,可以使用DataGridViewCellStyle.SelectionBackColor和DataGridViewCellStyle.SelectionForeColor属性.
例如,如果我像这样设置行单元格样式
row.DefaultCellStyle.BackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionForeColor = dataGridView1.ForeColor;
Run Code Online (Sandbox Code Playgroud)
我可以将此代码添加到 RowPostPaintEvent
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Selected)
{
using (Pen pen = new Pen(Color.Red))
{
int penWidth = 2;
pen.Width = penWidth;
int x = e.RowBounds.Left + (penWidth / 2);
int y = e.RowBounds.Top + (penWidth / 2);
int width = e.RowBounds.Width - penWidth;
int height = e.RowBounds.Height - penWidth;
e.Graphics.DrawRectangle(pen, x, y, width, height);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且选定的行将显示如下:

| 归档时间: |
|
| 查看次数: |
10213 次 |
| 最近记录: |