当我从数据库中获取数据时,行是有颜色编码的。但是当用户点击列进行排序时,颜色格式化被丢弃,所有行变为白色。我搜索答案,并发现一些人有相同的问题。他们实现了某种事件处理程序(如DataBindingComplete或CellFormatting),以便在排序后保留或重新实例化格式。然而,我无法让这个工作。有人可以解释为什么吗?或者告诉我另一种方法来解决这个问题?
这是从数据库获取数据并填充网格视图的代码。
这是我尝试重新启动格式化的方式。
这是从数据库获取数据并填充网格视图的代码。
public static OdbcConnection DbConnection; // Create an object for the DB connection
public static MainWindow mw = Form.ActiveForm as MainWindow;
public static void TestSqlToGridView()
{
// https://learn.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();
}
这是我尝试重新启动格式化的方式。
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();
}
但出现了一个问题,当我按列标题进行排序时,似乎事件从未被调用。我需要将其放在特定位置吗?
谢谢帮助!
mw.dataGridView.DataBindingComplete += dataGridView_DataBindingComplete;
。 - OhBeWise