DataGridView Sort On Column Click Messes Up CellFormatting

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have a DataGridView that uses the CellFormatting Event to render certain rows backcolor to red if they meet the specific criteria with the following code:<br/> <br/> <br/>
<pre lang="x-c# if (this.CallOffs.Columns[e.ColumnIndex].Name == "Pregnancy" ||
this.CallOffs.Columns[e.ColumnIndex].Name == "Accident" ||
this.CallOffs.Columns[e.ColumnIndex].Name == "Hospital" ||
this.CallOffs.Columns[e.ColumnIndex].Name == "Work_Related")
{
string strValue;

strValue = Convert.ToString(e.Value);

if (strValue.ToUpper().CompareTo("YES") == 0)
{
int row = e.RowIndex;

this.CallOffs.Rows[row].DefaultCellStyle.BackColor = Color.Red;
}
}
else if (this.CallOffs.Columns[e.ColumnIndex].Name.ToUpper() == "ABSENCE_DATE")
{
string AbsenceDate = Convert.ToString(e.Value);
string ReturnDate = Convert.ToString(this.CallOffs.Rows[e.RowIndex].Cells["RETURN_DATE"].Value);


if (AbsenceDate != string.Empty && ReturnDate != string.Empty)
{
try
{
DateTime dateAbsence;
DateTime dateReturn;

dateAbsence = DateTime.ParseExact(AbsenceDate, "MMddyy", System.Globalization.CultureInfo.InvariantCulture);
dateReturn = DateTime.ParseExact(ReturnDate, "MMddyy", System.Globalization.CultureInfo.InvariantCulture);

TimeSpan DateDiff = dateReturn - dateAbsence;

if (DateDiff.Days >= 3)
{
int row = e.RowIndex;

this.CallOffs.Rows[row].DefaultCellStyle.BackColor = Color.Red;
}
}
catch (Exception ex)
{
MessageBox.Show("Error Attempting To Parse Dates: ABSENCE_DATE = " + AbsenceDate + ", RETURN_DATE = " + ReturnDate + "nn" + ex.Message);
return;
}
}
}[/code]
<br/> <br/> But when I click one of the column headers to sort a particular column in my DataGridView, all of the rows become red even though they dont meet my criteria.  How do I fix this so the rows that are highlighted remain highlighted and the ones that arent suppose to be highlighted remain as they are.  Thank you!

View the full article
 
Back
Top