2011-08-30 159 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),本週的得分是在第二列]