Cannot use Color.FromArgb in DataGridView cell BackColor

早过忘川 提交于 2019-12-23 23:08:50

问题


I am looping through a DataGridView control and adding rows dynamically. I am setting the BackColor property of each cell based on the following logic:

if (bidVolume != null)
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.Green;
}
else
{
    this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.FromArgb(150, Color.Green);
}

This is causing problems, the color is not properly set visually and when re-sizing the DataGridView it looks like this:

When I don't use Color.FromArgb and just use Color.Red for example, then everything works fine ..

Is it possible to set a cell BackColor using Color.FromArgb ?

Thanks


回答1:


You cannot use Color.FromArgb, because DataGridView won't accept transparent colors. This is probably caused by the fact that the cells and DataGridView are not transparent (by default). What you are looking for is probalby this; you may want to set BackColor to color between White and Green.

If I am mistaken and this is not what you want please explain your need for alpha channel in the cell.




回答2:


You got the reason why. To overcome this, use the protected SetStyle method to override the behaviour. Something like:

class MyDgv : DataGridView
{
    public MyDgv()
    {
        this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); //this is the key

        //and now you can do what you want.
        this.Rows[this.RowCount - 1].Cells[1].Style.BackColor = Color.FromArgb(150, Color.Green);
    }
}

From documentation:

The BackColor property does not support transparent colors unless the SupportsTransparentBackColor value of System.Windows.Forms.ControlStyles is set to true.

The BackColor property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control. For example, a Button will have the same BackColor as its parent Form by default. For more information about ambient properties, see the AmbientProperties class or the Control class overview.



来源:https://stackoverflow.com/questions/17131996/cannot-use-color-fromargb-in-datagridview-cell-backcolor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!