2014-04-18 37 views
1

我有网格,我们正在从我的sql数据库中获取数据透视表。现在我需要根据它们的单元格值为gridview单元格赋予不同的颜色。请为我提供这个需求的c#代码。如何根据单元格值更改gridview单元格的颜色?

----------------------------------------------- 
Alternative Goal 1 Goal 2 Goal 3 Goal 4 
----------------------------------------------- 
A   0.86 0.5  1 0.5  
B   0.87 0 0.9  0.6  
---------------------------------------------- 

现在根据值的颜色就会像下面

Value     Colour Code 
---------------------------------- 
1.00     33B739 
0.75 to 0.99   50EB19 
0.50 to 0.74   54EA58 
0.25 to 0.49   93FB85 
0.05 to 0.24   E0FCE0 
0.00     FFFFFF 
-0.24 to -0.05   FFD5D5 
-0.49 to -0.25   FFA3A3 
-0.74 to -0.50   FF6161 
-0.99 to -0.75   FF3333 
-1.00     FF0000 
--------------------------------- 
+0

尝试将其存储在任何#temp表中,然后使用between子句或>/<运算符检索值。 – Shell

回答

0

不知道它是否仍然是相关的,但我会做这样的:

public partial class Form1 : Form { 

    public Form1() { 
     InitializeComponent(); 

     List<ColorMap> colorMaps = new List<ColorMap>() 
     { 
      new ColorMap(-999, -1, "FF0000"), 
      new ColorMap(-0.99, -0.75, "FF3333") 
      /* and so on*/ 
     }; 

     foreach (DataGridViewRow row in dataGridView1.Rows) { 
      foreach (DataGridViewCell cell in row.Cells) { 
       double cellValue; 
       if (!double.TryParse(cell.Value.ToString(), out cellValue)) { 
        continue;//or whatever logic you want 
       } 
       ColorMap colorMap = colorMaps.SingleOrDefault(x => x.From <= cellValue && x.To >= cellValue); 
       if (colorMap == null) { 
        continue;//or whatever logic you want 
       } 

       ColorCode colorCode = new ColorCode(colorMap.Value); 
       cell.Style.BackColor = Color.FromArgb(colorCode.Red, colorCode.Green, colorCode.Blue); 
      } 
     } 
    } 
} 

public class ColorMap { 
    public double From { get; private set; }//lowest border 
    public double To { get; private set; }//highest border 
    public string Value { get; private set; }//color code 

    public ColorMap(double from, double to, string value) { 
     this.From = @from; 
     this.To = to; 
     this.Value = value; 
    } 
} 

public class ColorCode { 
    public string Color { get; private set; } 

    public ColorCode(string code) { 
     this.Color = code; 
    } 

    public int Red { get { return ConvertToInt(0, 1); } } 
    public int Green { get { return ConvertToInt(2, 3); } } 
    public int Blue { get { return ConvertToInt(4, 5); } } 

    private int ConvertToInt(int index1, int index2) { 
     if (Color == null || Color.Length != 6) { 
      return 0;//or whatever logic you want 
     } 
     string hexValue = string.Format("{0}{1}", Color[index1], Color[index2]); 
     int result; 
     try { 
      result = int.Parse(hexValue, NumberStyles.HexNumber); 
     } catch { 
      return 0; 
     } 
     return result; 
    } 
} 

我希望你的数据库表对于最低值和最高值都有单独的字段,因为它会更容易阅读。

+0

thx为您的答复,但我将只使用这些颜色值的条件。 db中没有提到这些最大值和最小值。 – vim

相关问题