Set datagrid view background to transparent

后端 未结 5 1618
萌比男神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:41

    i did this with Deumber's solution and it works, but causes some troubles that i avoided by adding small improvements:

    A. scrolling the DGV messes up the background. solution: put this somewhere:

    public partial class main : Form
    { 
        protected override CreateParams CreateParams 
        {
        get
            {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x02000000;
            return cp;
            }
        }
    }
    

    the background will still scroll, but be corrected immediately after each scroll step. it's noticeable, but was acceptable for me. does anyone know a better solution to support scrolling with this?

    B. the designer has troubles using it. solution:

    protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds)
    {
        base.PaintBackground(graphics, clipBounds, gridBounds);
        if (main.ActiveForm != null && this.Parent.BackgroundImage != null)
        {
            Rectangle rectSource = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height);
            Rectangle rectDest = new Rectangle(-3, 3, 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();
        }
    }
    

    now the designer treats it just like a DGV. it will fail if you ever want to draw the DGV while you have no ActiveForm, but that's not the case usually. it's also possible to just keep the if-line while you might still want to use the designer, and delete it for the release.

提交回复
热议问题