DataGridView比较结果

时间:2011-08-30 16:54:18

标签: c# datagridview

我正在使用DataGridView来获得一些得分结果。但我应该将结果与上周的结果进行比较,并将其设为绿色或红色....如果可能的话,在值前加上差值。

EG。 1400 +10

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

以前有人试过吗?

由于

1 个答案:

答案 0 :(得分:1)

使用您的DataGridView的CellFormatting事件来设置BackColor和您想要显示的自定义文字。

当事件触发显示本周分数的列中的单元格时,您将进行格式化。尝试将此值和上周分数(在同一行的另一列中)的值转换为int,然后进行比较。如果差异不为零,请使用事件的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),本周的分数显示在第二列]