DataGridView单元格的透明SelectionBackColor [英] Transparent SelectionBackColor for DataGridView Cell

查看:458
本文介绍了DataGridView单元格的透明SelectionBackColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows Forms DataGridView中,我试图使选定的行具有粗体并且不更改背景颜色。

In a Windows Forms DataGridView I'm trying to make the selected row have bold font and not change the background color.

为此,我使用了以下代码:

For that matter I used the following code:

// This method is used to load the data into the grid
private void GridLoad()
{
    // Configures the Data Source

    Grid.DefaultCellStyle.SelectionBackColor = Color.Transparent;

    Grid.ClearSelection();          
}

private void Grid_SelectionChanged(object sender, EventArgs e)
{
    var dataGridView = Grid;

    foreach (DataGridViewRow row in dataGrid.Rows)
    {
        row.DefaultCellStyle.Font = dataGrid.Font;
    }

    if (dataGridView.SelectedRows.Count > 0)
    {
        var selectedRow = dataGridView.SelectedRows[0];
        selectedRow.DefaultCellStyle.Font = new Font(dataGridView.Font, FontStyle.Bold);
    }            
}

当我单击其中一行时,代码有效要选择它,字体将变为粗体,但有一个重叠。

The code works, when I click one of the rows to select it, the font becomes bold, but there is one overlap.

文本被复制,似乎常规字体的原始文本保留在背景上,而新文本

The text gets duplicated, it seems the original text in regular font stays on background and the new text on bold appears on top slightly displaced to the right.

为什么会发生?为什么会发生这种重叠以及如何解决呢?

Why is it happening? Why this overlap is happening and how do I solve it?

推荐答案

主要问题在以下一行:

dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Transparent;

将其删除,然后渲染就没有问题了。

Remove it and then you will have no problem in rendering.

不要将 SelectionBackColor 设置为 Color.Transparent ,如果您想拥有一个透明的选择背景色,只要将 SelectionBackColor 设置为与<$ c $相同的值就足够了c> BackColor 。

Don't set SelectionBackColor to Color.Transparent, if you want to have a If you don't want to have a transparent selection back color for cells, it's enough to set SelectionBackColor to the same value as BackColor of the cell.

为此目的更合适的事件是 CellFormatting DataGridView 事件。使用此事件,您可以为单元格提供动态格式设置:

A more suitable event for such purpose is CellFormatting event of DataGridView. Using this event you can provide dynamic formatting for cells:

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
        this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
    {
        e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
        e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor;
        e.CellStyle.SelectionBackColor = e.CellStyle.BackColor;
    }
    else
    {
        e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Regular);
    }
}

这篇关于DataGridView单元格的透明SelectionBackColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆