DataGridView row: Semi-transparent selection or row border on selection

前端 未结 1 1578
予麋鹿
予麋鹿 2021-02-14 01:42

I have a DataGridView where the background of each row is different depending on the data bound item. Though, when I select a row, I can no longer see its original background co

相关标签:
1条回答
  • 2021-02-14 02:24

    If you want to draw a border around selected rows, you can use the DataGridView.RowPostPaintEvent, and to 'clear' the selection colors, you can use the DataGridViewCellStyle.SelectionBackColor and DataGridViewCellStyle.SelectionForeColor properties.

    For example, if I set the row cell style like this

    row.DefaultCellStyle.BackColor = Color.LightBlue;
    row.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
    row.DefaultCellStyle.SelectionForeColor = dataGridView1.ForeColor;
    

    I can add this code to the 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);
            }
        }
    }
    

    and a selected row will display like this:

    row with border

    0 讨论(0)
提交回复
热议问题