以下是将DataGridView数据绑定到chart扇形图上的一种实现思路。
/// <summary>
/// 绘制扇形图
/// </summary>
/// <param name="count">dgv的行数</param>
private void PainAlam(int count)
{
Hashtable ht = new Hashtable();
//第一次遍历所有警报,存入到哈希表里面,value设置为1。value为已出现报警的次数
for (int i = 0; i < count; i++)
{
var item = DgvReportData.Rows[i].Cells["alarmname"].Value; //每次访问DgvReportData第i行第alarmname的列的值
if (ht.Contains(item))
{
//如果该警报已经存在则改变对应的value值 + 1
int tmp = (int)ht[key: item];
ht[item] = 1 + tmp;
}
else
ht.Add(item, 1);
}
string[] x = new string[count];
double[] y = new double[count];
//第二次遍历哈希表,给数据源赋值。value/count就是报警出现次数的百分比
ICollection key = ht.Keys;
int sub = 0;
foreach (string item in key)
{
int value = (int)ht[key: item];
y[sub] = value;
string percent = ((value*100)/(count)).ToString();
x[sub] = item + " 占 " + percent + "%";
sub++;
}
//将两个数据源绑定到chart1
chtAlam.Series["Series1"].Points.DataBindXY(x, y);
}