Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms: DataGridView Problem with backgroundcolor after sorting

I have a Windows Forms datagridview, where the rows have different background-colors.

The problem is, that the background-colors disappear after sorting (click on a row header) and all rows are again white (default color). What could be the reason for this problem?

like image 663
Elmex Avatar asked Jun 08 '11 12:06

Elmex


2 Answers

According to this bug report submitted to Microsoft on June 2005 this is by design for Visual Studio 2005:

Thank you for your bug report. The behavior you notice is by design. Sorting a databound grid causes all rows to be recreated (called a ListChangedType.Reset). This causes your formatting to be lost. You need to use the DataBindingComplete event to apply styles and check for the ListChangedType.Reset to know when to apply your styling. Alternatively you can use the CellFormatting event. Ideally all your formatting can be done inside the CellFormatting since it is applied dynamically.

like image 77
Jay Riggs Avatar answered Nov 13 '22 00:11

Jay Riggs


Use Sorted event and you can restore backcolor of your datagridview.

private void datagridview_Sorted(object sender, EventArgs e)
{
    //you can restore backcolor of datagridview in this function.
   //example given below
    foreach (DataGridViewRow r in datagridview.Rows)
        r.DefaultCellStyle.BackColor = Color.FromArgb(220, 0, 0);            
}
like image 24
Pratig Avatar answered Nov 13 '22 00:11

Pratig