我有一个C#程序,需要显示一个包含2个serie对象的图表。目前我只有一个包含2个数据表的数据集。这两个表具有相同的布局。我将数据集绑定到图表的datasource属性并执行databind()方法。它只显示一个系列。
我认为解决方案在于定义自定义bindingcontext,但我似乎无法弄明白。有人能帮帮我吗?感谢。
以下是我的一些代码:
DataSet dataSet = new DataSet();
DataTable dataTable = database.Query("select sum(amount) as monthamount, month(transdate) as month from transaction where year(transdate)=" + balanceDateTimePicker.Value.Year + " group by month");
dataSet.Tables.Add(dataTable);
dataTable = database.Query("select sum(amount) as monthamount, month(transdate) as month from transaction where year(transdate)=" + balanceDateTimePicker.Value.AddYears(-1).Year + " group by month");
dataSet.Tables.Add(dataTable);
reoccuranceChart.DataSource = dataSet;
System.Windows.Forms.DataVisualization.Charting.Series series = reoccuranceChart.Series["Series1"];
series.XValueMember = "month";
series.YValueMembers = "monthamount";
series.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
series.IsVisibleInLegend = false;
series = reoccuranceChart.Series["Series2"];
series.XValueMember = "month";
series.YValueMembers = "monthamount";
series.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
series.IsVisibleInLegend = false;
reoccuranceChart.DataBind();
答案 0 :(得分:2)
我找到了。它实际上相当简单。 我所要做的就是单独绑定系列点:
DataSet dataSet = new DataSet();
DataTable dataTable = database.Query("select sum(amount) as monthamount, month(transdate) as month from transaction where year(transdate)=" + balanceDateTimePicker.Value.Year + " group by month");
dataSet.Tables.Add(dataTable);
dataTable = database.Query("select sum(amount) as monthamount, month(transdate) as month from transaction where year(transdate)=" + balanceDateTimePicker.Value.AddYears(-1).Year + " group by month");
dataSet.Tables.Add(dataTable);
System.Windows.Forms.DataVisualization.Charting.Series series = reoccuranceChart.Series["Now"];
series.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
//series.IsVisibleInLegend = false;
series.Points.DataBind(dataSet.Tables[0].DefaultView, "month", "monthamount", "");
series = reoccuranceChart.Series["Last year"];
series.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
//series.IsVisibleInLegend = false;
series.Points.DataBind(dataSet.Tables[1].DefaultView, "month", "monthamount", "");
答案 1 :(得分:0)
我认为您的问题在于重用dataTable变量。您需要为第二个查询创建第二个DataTable以防止重新分配第一个查询,因为Add函数不会复制表中的数据,它只保存对它的引用。尝试更改:
dataTable = database.Query ...
到
DataTable dataTable2 = database.Query...
然后将其添加为第二个表,看看是否修复了它。