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);
}
}
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With