DataGridView rows can't change their background color at the initialization stage
I have the next problem: TabControl has three TabPages. Every TabPage has its own DataGridView. On "开发者_Go百科Enter" event some rows change their background color. When the form begin to initialize, the function, that changes color, is called. But DataGridView rows have their default background (background color hasn't been changed). If I click on another TabPage and then come back to the first TabPage the function is called again and the background is changed. So, why it doesn't happen at first time on the initialization stage (the function is called, but the rows don't change their color). How can I force the DataGridView to change the background color of its rows at the initialization stage? Thanks a lot!
I had same problem with DataGridViewCellStyle
, It seems there is a bug with TabControl
that when it has more than one tab, cellstyles
that are created with code are only applied to the first tab's DataGridView, so you can move your DataGridView
to the first tab or you can use the TabControl's SelectedIndexChanged
event and put your styling code in this event .
How are you changing the colour? You might want to look into the CellFormatting event to see whether you can explicitly paint the cell when it is visible to the user. That way each time it redraws the cell you can guarantee the colour will be correct. (Assuming you need different colours for the rows, otherwise just set the cell style and invalidate the control.
UPDATE:
It's important that you reference the cellstyle via the event args, otherwise you will do recursion to work out the cell style that you are trying to access.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
e.CellStyle.BackColor = Color.PaleGreen
}
I know this is an older question but I had a similar problem and had a hard time finding the answer. I ended up figuring it out on my own. My DGVs were on a tab control, so all I had to do was select my tab before applying my color change:
this.tabControl1.SelectedTab = tabPage2;
精彩评论