2011-08-30 108 views
-1

我正在使用DataGridView来放置一些评分结果。但是我应该将结果与上周的结果进行比较,并将结果与​​绿色或红色进行比较......如果可能,请在值前添加差异。DataGridView比较结果

例如, 1400 +10

在样本中用户有1400分,他比上周多了10分。

有没有人试过这种?

感谢

+1

是的,我有。但是,你的**问题**? –

+0

请勿将数据放入GrdView。将其存储为类的列表,然后使用GridView来显示它。 –

回答

1

用你的DataGridView的CellFormatting事件来设置要显示的BackColor和自定义文本。

当事件触发显示本周评分的列中的单元格时,您将进行格式设置。尝试将此值和上周得分(在同一行的另一列中)的值转换为int s,然后进行比较。如果差异不为零,请使用事件的CellStyleValue属性来自定义单元格的外观。

像这样:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { 
    if (e.ColumnIndex == 1) { 
     string lastScoreString = dataGridView1.Rows[e.RowIndex].Cells[0].Value as string; 
     int lastScore; 
     if (int.TryParse(lastScoreString, out lastScore)) { 
      string thisScoreString = dataGridView1.Rows[e.RowIndex].Cells[1].Value as string; 
      int thisScore; 
      if (int.TryParse(thisScoreString, out thisScore)) { 
       var scoreDifference = thisScore - lastScore; 
       var formattedScoreText = string.Format("{0} {1}", thisScore, scoreDifference.ToString("+#;-#;0")); 
       if (scoreDifference > 0) { 
        e.CellStyle.BackColor = Color.Green; 
        e.CellStyle.ForeColor = Color.White; // <-- Me expressing my artistic self. 
        e.Value = formattedScoreText; 
       } else if (scoreDifference < 0) { 
        e.CellStyle.BackColor = Color.Red; 
        e.Value = formattedScoreText; 
       } 
      } 
     } else { 
      //TODO Can't parse this week score. 
     } 
    } else { 
     //TODO Can't parse last week score. 
    } 
} 

[代码假定上周的成绩显示在第一列(索引位置0),本周的得分是在第二列]