1
votes

I'm creating a datagridview transparent

//I got the parent background image

Bitmap parentBackGround = new Bitmap(this.Parent.BackgroundImage);

//Set the area i want to create equal to the size of my grid

Rectangle rect = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height);

//And draw in the entire grid the area of the background image that is cover with my grid, making a "transparent" effect.

graphics.DrawImage(parentBackGround.Clone(rect, PixelFormat.Format32bppRgb), gridBounds);

When the backgroundimage of the grid's parent is show in an normal layout all work ok, but if the layout is stretch, center or any other, the transparency effent gone, have you any idea to fix it?

2

2 Answers

0
votes

Well i create a bitmap and copy the background image of the form parent of the grid in it exactly size, and then use only the part it cover my grid.

I inherit from grid and override those methods:

    protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds)
    {
        base.PaintBackground(graphics, clipBounds, gridBounds);
        if (DesignMode) return;

        Control tmpParent = Parent;
        int locationX = this.Location.X;
        int locationY = this.Location.Y;
        while (tmpParent.BackgroundImage == null)
        {
            locationX += tmpParent.Location.X;
            locationY += tmpParent.Location.Y;
            tmpParent = tmpParent.Parent;
        }

        Rectangle rectSource = new Rectangle(locationX, locationY, this.Width, this.Height);
        Rectangle rectDest = new Rectangle(0, 0, rectSource.Width, rectSource.Height);

        Bitmap b = new Bitmap(tmpParent.ClientRectangle.Width, tmpParent.ClientRectangle.Height);

        Graphics.FromImage(b).DrawImage(tmpParent.BackgroundImage, tmpParent.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;
        }
    }