2017-05-30 592 views
1

我试图用列值的名称来标记我的饼图(在这种情况下,这将是机器名称和它旁边的百分比),这是相当困难的。默认情况下,在C#中,我从MySQL数据库绘制它基于列“机器”上采集数据,而下面是我目前拥有的代码,这将只显示百分比:在c#中的饼图标签的文字和百分比

string DatabaseCountMachines = "SELECT Machine, COUNT(*) total FROM completed GROUP BY Machine"; 

MySqlConnection conDataBase = new MySqlConnection(constring); 
MySqlCommand cmdDataBase = new MySqlCommand(DatabaseCountMachines, conDataBase); 
MySqlDataReader StatsbyMachine; 

try 
{ 
    conDataBase.Open(); 
    StatsbyMachine = cmdDataBase.ExecuteReader(); 

    while (StatsbyMachine.Read()) 
    { 
     this.chartMachine.Series["Series1"].Points.AddXY(StatsbyMachine.GetString("Machine"), StatsbyMachine.GetString("total")); 
     this.chartMachine.Series["Series1"].CustomProperties = "PieLabelStyle=Outside"; 
     this.chartMachine.Series["Series1"].Label = "#LEGENDTEXT" + "#PERCENT";  
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message); 
} 
+0

在饼图中,x值不适用。 (你可以使用'AddY')你可以显示你想要的图像吗? – TaW

回答

1

馅饼图x-values不适用所以他们不显示...你可能还不如使用AddY

只需将两个数据添加到每个DataPointLabel

变化

chartMachine.Series["Series1"].Points 
      .AddXY(StatsbyMachine.GetString("Machine"), StatsbyMachine.GetString("total")); 

int index = chartMachine.Series["Series1"].Points.AddY(StatsbyMachine.GetString("total")); 
chartMachine.Series["Series1"].Points[index].Label = 
     StatsbyMachine.GetString("Machine") + " : " + StatsbyMachine.GetString("total"); 

请注意,虽然字符串添加为y值将被转换为数字,这将不适用于x值,即使您使用使用x值的图表类型。

某些图表数据不需要数字x值,如姓名,城市甚至ID,因此不会自动转换,即使在可能的情况下也是如此。

Y值otoh总是需要数字,否则图表的整个想法是没有意义的。因此,如果可能的话,您的string total将被转换为数字。如果转换失败,值将为0 ..

+1

我得到一个错误,说这个代码不能隐式地将类型字符串转换为System.Windows.Forms.DataVisualization.Charting.DataPoint。该链接显示了我想要做的一个例子:http://www.fusioncharts.com/dev/chart-guide/pie-and-doughnut-charts/configuring-pie-and-doughnut-charts.html – LitteringAnd

+0

Ouch,我已经省去了'Label'部分!,更正..对不起。 – TaW

+1

我将'StatsbyMachine.GetString(“total”)'更改为'#PERCENT'。完美的作品。做得好。 – LitteringAnd