2014-04-18 205 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

相關問題