Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView row's background color is not changing

I want to change the background color of the DGV's row based on particular condition at load even in Windows Form. But I can't see any change of color to any DGV's row. Could anyone tell me how can I solve this problem?

private void frmSecondaryPumps_Load(object sender, EventArgs e)
{
            try
            {
                DataTable dt = DeviceData.BindData("SECONDARY_PUMPS".ToUpper());
                dataGridView1.DataSource = dt;

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewColumn column in dataGridView1.Columns)
                    {
                        if (row.Cells[column.Name] != null)
                        {
                            if (row.Cells[column.Name].Value.ToString() == "ON")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Green;

                            if (row.Cells[column.Name].Value.ToString() == "OFF")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                        }
                    }
                }

                dataGridView1.Refresh();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
like image 820
Stardust Avatar asked Mar 02 '12 04:03

Stardust


2 Answers

One of the problems with using either the cellformatting, databindingcomplete or even paint events is that they get fired multiple times. From what I've gathered, there is an issue with the datagridview control in that you cannot change the color of any of the cells until AFTER the form has been shown. Thus methods that run, or events that fire before Shown() is called will not change the color. The events that are sited as the solution to the problem usually work, but since they're called many times, may not be the most efficient answer.

Probably the simplest solution to the issue is to put your code to fill/color your grids in the Shown() method of your form instead of the constructor. Below is a link to a post in the msdn forums that tipped me off to the solution, it's marked as the answer about 3/4 of the way down the page.

MSDN forums post with the Solution

like image 170
King_Rob Avatar answered Sep 28 '22 07:09

King_Rob


I think the best place would be to set the BackColor in the CellFormatting event of the DataGridView, something on these lines.

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index
    // check the cell value under your specific column and then you can toggle your colors
    row.DefaultCellStyle.BackColor = Color.Green;
}
like image 37
V4Vendetta Avatar answered Sep 28 '22 09:09

V4Vendetta