Set datagrid view background to transparent

后端 未结 5 1616
萌比男神i
萌比男神i 2020-12-11 07:04

I tried to set the background color of a data grid view to be \"transparent\" from properties but it it said \"not a valid property\".

How can I do it?

5条回答
  •  时光取名叫无心
    2020-12-11 07:49

    I did this solution to a specific problem (when the grid was contained in a form with background image) with simples modifications you can adapt it to create a generic transparent Grid, just ask if the parent have background image, else just use the parent backcolor to paint your grid, and that is all.

    You must inherit from DataGridView and override the PaintBackground method like this:

    protected override void PaintBackground(Graphics graphics, Rectangle clipBounds,  Rectangle gridBounds)
      {
        base.PaintBackground(graphics, clipBounds, gridBounds);
        Rectangle rectSource = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height);
        Rectangle rectDest = new Rectangle(0, 0, rectSource.Width, rectSource.Height);
    
        Bitmap b = new Bitmap(Parent.ClientRectangle.Width, Parent.ClientRectangle.Height);
        Graphics.FromImage(b).DrawImage(this.Parent.BackgroundImage, Parent.ClientRectangle);
    
    
        graphics.DrawImage(b, rectDest, rectSource, GraphicsUnit.Pixel);
        SetCellsTransparent();
      }
    
    
    public void SetCellsTransparent()
    {
        this.EnableHeadersVisualStyles = false;
        this.ColumnHeadersDefaultCellStyle.BackColor = Color.Transparent;
        this.RowHeadersDefaultCellStyle.BackColor = Color.Transparent;
    
    
        foreach (DataGridViewColumn col in this.Columns)
        {
            col.DefaultCellStyle.BackColor = Color.Transparent;
            col.DefaultCellStyle.SelectionBackColor = Color.Transparent;
        }
    }
    

提交回复
热议问题