When I fetch data from the database the rows are colorcoded. However when the user clicks on the columns to sort the color formatting is discarded and all the rows become white. I've searched for answers and found some people with the same issue as I. They have implemented some kind of eventhandler (such as DataBindingComplete
or CellFormatting
) in order to keep or re-instantiate the formatting after the sort. However I don't get this to work. Can someone explain why, or tell me another way I can solve this problem?
This is the code that fetch data from the database and fills the gridview
public static OdbcConnection DbConnection; // Create an object for the DB connection
public static MainWindow mw = Form.ActiveForm as MainWindow;
public static void TestSqlToGridView()
{
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.datasource?view=netframework-4.7.1
//var mw = Form.ActiveForm as MainWindow;
ConnectToDB();
DbConnection.Open();
BindingSource bindingSource = new BindingSource();
// Automatically generate the DataGridView columns.
SuspendDrawing(mw.dataGridView); // wait with drawing until all data is read
bindingSource.DataSource = GetData( Laddstatus() );
mw.dataGridView.DataSource = bindingSource;
SetRowColor(); // Change the rows color
mw.dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader; // Adjusting the size of header cells !!! AllCells = SLOW !!!
ResumeDrawing(mw.dataGridView); // draw all cells
// Set the DataGridView control's border.
mw.dataGridView.BorderStyle = BorderStyle.Fixed3D;
DbConnection.Close();
}
This is the way I tried to reinitiate the formatting
void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
// This event is raised when the contents of the data source
// change or when the value of the DataSource, DataMember, or BindingContext
// property changes.
Print("DatabindingComplete!"); //DEBUG
SetRowColor();
}
But for some reason when I press the column headers to sort it seem like the event is never called. Do I have to put in a specific location?
Thanks for the help!