我有网格,我们从我的sql数据库获取数据透视表。现在我需要根据它们的单元格值为gridview单元格提供不同的颜色。请帮我解决此要求的c#代码。
-----------------------------------------------
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 :(得分: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;
}
}
我希望您的数据库表具有最低值和最高值的单独字段,因为它更容易阅读。