首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataGridView行:半透明选择或选择上的行边框

DataGridView行:半透明选择或选择上的行边框
EN

Stack Overflow用户
提问于 2010-12-15 18:31:36
回答 1查看 11.5K关注 0票数 11

我有一个DataGridView,其中每一行的背景都根据数据绑定项的不同而不同。但是,当我选择一行时,我再也看不到它原来的背景色了。

为了解决这个问题,我想到了两个解决方案:

我可以将选择设置为半透明的,这样就可以查看两个选定的行是否具有不同的背景颜色。

或者,我可以完全删除选择颜色,并在所选行周围画一个边框。

哪个选项更简单,我该如何做?

这是一个WinForm应用程序。

编辑:我最终使用了你的一些代码

代码语言:javascript
复制
    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);
        }
    }

这给人一种半透明的选择颜色的印象。谢谢你的帮忙!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-16 03:10:23

如果要在选定行周围绘制边框,可以使用DataGridView.RowPostPaintEvent,而要“清除”选择颜色,可以使用DataGridViewCellStyle.SelectionBackColorDataGridViewCellStyle.SelectionForeColor属性。

例如,如果我像这样设置行单元格样式

代码语言:javascript
复制
row.DefaultCellStyle.BackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
row.DefaultCellStyle.SelectionForeColor = dataGridView1.ForeColor;

我可以将这段代码添加到RowPostPaintEvent

代码语言:javascript
复制
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);
        }
    }
}

选定的行将显示如下:

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4448945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档