using datagridview_cellformatting in C# with data that is databound to change background color

  • Thread starter Thread starter bosco dog
  • Start date Start date
B

bosco dog

Guest
Good Evening:


I have loaded data from a datatable using SQL Server database into a datagridview. I am trying
to change the background color of the datagridview based on the results in the first
column. It works, but it seems odd because when I trace through the code, it goes through
the datagridview_cellformatting code numerous times (like 30 or 40 times) when there are only about
9 or 10 rows. Is this normal? Or can someone tell me what is wrong with my code?

I am using visual Studio 2010 on Windows 10.


Thank you very much.

Sincerely,

Bosco Dog

private void holidaySchedDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{


try
{
foreach(DataGridViewRow row in holidaySchedDataGridView.Rows)
{

if (row.Cells["HolidayApproval"].Value != null)
{

if (row.Cells["HolidayApproval"].Value.ToString().Equals(ApprovalStatus.Denied.ToString(), StringComparison.Ordinal))
{

row.DefaultCellStyle.BackColor = Color.Salmon;
row.DefaultCellStyle.ForeColor = Color.Black;

}
else if (row.Cells["HolidayApproval"].Value.ToString().Equals(ApprovalStatus.Pending.ToString(), StringComparison.Ordinal))
{

row.DefaultCellStyle.BackColor = Color.Yellow;
row.DefaultCellStyle.ForeColor = Color.Black;

}

else if (row.Cells["HolidayApproval"].Value.ToString().Equals(ApprovalStatus.Approved.ToString(), StringComparison.Ordinal))
{

row.DefaultCellStyle.BackColor = Color.Black;
row.DefaultCellStyle.ForeColor = Color.White;
}
}
}
}
catch (FormatException fmEx)
{
MessageBox.Show(fmEx.Message);
}
catch (SystemException sysEx)
{
MessageBox.Show(sysEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}

Continue reading...
 
Back
Top