C# datagridview. Cell backcolor is empty dispite of DefaultCellStyle

一个人想着一个人 提交于 2021-01-28 12:05:18

问题


I set the cell background color in a datagridview to yellow via

`grid.DefaultCellStyle.BackColor = Color.Yellow;`

I see the yellow cells but should the back color property of the cell not also be yellow? I get an "Color[Empty]" instead of color yellow. Why is the color not Yellow if I try the following code? grid.CellClick += new DataGridViewCellEventHandler( (eventsource, cellevent) => { int rowIndex = cellevent.RowIndex; int colIndex = cellevent.ColumnIndex; MessageBox.Show(" color: "+ grid.Rows[rowIndex].Cells[colIndex].Style.BackColor); });


回答1:


should the back color property of the cell not also be yellow?

No, it should not.

Note that you can set each cell's BackColor individually to some other color that the default color. When it is set it takes precedence over the default. Color.Emtpy is an extra values that means: display the default color.

MSDN:

Color Empty   :   Specifies whether this Color structure is uninitialized.

To find out what is displayed you can simply test for it:

Color c = someCell.Style.BackColor == Color.Emtpy ? 
          dgv.DefaultCellStyle.BackColor: someCell.Style.BackColor;

Another way to test is the color.IsEmpty function.

And you can also reset a color you have set to the default color by setting it to Color.Emtpy. And when the default color changes it will change also.

Example:

You want to mark cell with issues with a rosy back color. The default color is light gray until user enters edit mode; then is changes to white.

The rosy cells will not follow because they have an individual color set.

After correcting the issue the user leaves the cell and you reset its color: But not to white but to Color.Empty.

Now when the user leaves edit mode all cells without issues turn back to the default browse color light gray..



来源:https://stackoverflow.com/questions/50213063/c-sharp-datagridview-cell-backcolor-is-empty-dispite-of-defaultcellstyle

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