C#: Update DatagridView Cell style based on row data

Categories: Development Notes; Tagged with: ; @ January 16th, 2013 17:58

Requirement

Change the cell background colour to red when the data…

image

Solution

Listening to the DataGridView.CellFormatting Event, based on the data, update the cell style in runtime.

Details

1. Add Listener:

 this.dataGridViewForLogs.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dataGridViewForLogs_CellFormatting);

2. The hanlder:

        private void dataGridViewForLogs_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value == null)
            {
                return;
            }

            if (dataGridViewForLogs.Columns[e.ColumnIndex].Name.Equals("result"))
            {
                String logResult = e.Value.ToString();
                if (logResult != null && logResult.Contains("FAIL"))
                {
                    e.CellStyle.BackColor = Color.Red;
                    e.CellStyle.ForeColor = Color.White;
                    e.CellStyle.SelectionBackColor = Color.Navy;
                    return;
                }
            } 
            e.CellStyle.BackColor = Color.White;

        }

 

links:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.