CodexBloom - Programming Q&A Platform

WinForms DataGridView Cell Formatting Based on External Data Source Not Updating Correctly

👀 Views: 50 💬 Answers: 1 📅 Created: 2025-08-25
winforms datagridview cellformatting C#

I'm wondering if anyone has experience with I'm working through a tutorial and I am facing an issue with a `DataGridView` in my WinForms application where I want to dynamically format cell colors based on conditions from an external data source (a database)... Although I've implemented the `CellFormatting` event, the colors don’t seem to update correctly when the underlying data changes. Here’s a simplified version of my code: ```csharp private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name == "Status") { var status = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; if (status == "Pending") { e.CellStyle.BackColor = Color.Yellow; } else if (status == "Completed") { e.CellStyle.BackColor = Color.Green; } else if (status == "Failed") { e.CellStyle.BackColor = Color.Red; } } } ``` Furthermore, I am fetching the data from a SQL database and rebinding the DataGridView after every update. Here’s the code where I rebind the data: ```csharp private void UpdateDataGrid() { var data = GetDataFromDatabase(); // Imagine this fetches data from a database dataGridView1.DataSource = data; dataGridView1.Refresh(); // I have tried calling Refresh() here, but it doesn’t help. } ``` I noticed that when the `DataSource` is set again, even if the data remains the same, the cell formatting does not trigger. I have also ensured that the `CellFormatting` event is correctly hooked up in the constructor: ```csharp public MainForm() { InitializeComponent(); dataGridView1.CellFormatting += dataGridView1_CellFormatting; } ``` When I run the application, I see that the data updates in the grid, but the cell colors remain the same as they were before the update. Is there anything I might be missing here? Is there a better approach to ensure that cell formatting reflects the latest data state? Any help would be greatly appreciated! Any examples would be super helpful. I'm working in a Ubuntu 20.04 environment.