【发布时间】:2013-01-28 00:44:23
【问题描述】:
我有一个 C# WinForms 应用程序,它有四个图表控件,用于以图形方式显示一些分析结果。
我的代码适用于每个图表,但是为了提高效率和重用代码,我定义了一个代码块:
- 创建所需的系列,
- 从数据库中提取数据并将结果分配给适当的系列
- 将系列添加到图表中
- 自定义图表外观。
上述所有操作都是动态完成的,因为数据在设计时不存在。
我希望重用的工作代码是:
// Add both series to the chart.
ChartName.Series.AddRange(new Series[] { series1, series2 });
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)ChartName.Diagram;
我想将ChartName 对象更改为一个变量,我可以传递每个图表以重用代码。类似的东西(注意这不起作用):-
var VChart = this.Controls.Find(ChartName, true);
// Add both series to the chart.
VChart.Series.AddRange(new Series[] { series1, series2 });
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)VChart.Diagram;
任何关于如何将变量传递到 ChartName 的想法、提示、技巧等将不胜感激。
完整代码:
void Generate_Chart()
{
// Create two stacked bar series.
Series series1 = new Series("Data", ViewType.Bar);
Series series2 = new Series("Ben", ViewType.Line);
try
{
using (var cmd = new SQLiteCommand(m_dbConnection))
for (int i = LoopMin; i < LoopMax; i++)
{
// Retrieve the actual calculated values from the database
cmd.CommandText = "SELECT " + Chart_SourceActualValue + " FROM " + Chart_SourceTable + " WHERE Value = " + i + "";
Chart_SeriesA_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Retrieve the expected values from the database
cmd.CommandText = "SELECT " + Chart_BenExpValue + " FROM " + Chart_SourceTable + " WHERE Value = " + i + "";
Chart_SeriesB_Value = Convert.ToInt32(cmd.ExecuteScalar());
// Add the dynamically created values to a series point for the chart
series1.Points.Add(new SeriesPoint(i, Chart_SeriesA_Value));
series2.Points.Add(new SeriesPoint(i, Chart_SeriesB_Value));
}
}
catch (Exception)
{
throw;
}
// Add both series to the chart.
//this.Controls.Find(varChart, true)
ChartName.Series.AddRange(new Series[] { series1, series2 });
// Remove the GridLines from the chart for better UI
// Cast the chart's diagram to the XYDiagram type, to access its axes.
XYDiagram diagram = (XYDiagram)ChartName.Diagram;
// Customize the appearance of the axes' grid lines.
diagram.AxisX.GridLines.Visible = false;
}
}
【问题讨论】:
-
“将变量传递到 ChartName”是什么意思?
-
我使用
ref关键字做了类似的事情来创建泛型方法 -
我想重新使用一个变量将 ChartName 传递到系列代码段和 XYDiagram 段中。本质上,我希望对所有四个图表都使用相同的两行代码,而不是八行代码做同样的事情,唯一的区别是 ChartName。
-
把它放到一个以chartName为参数的函数中?
-
我不确定您使用的是什么图表包,但向前迈出的一步是将您重新获取图表更改为
var VChart = this.Controls.Find(ChartName, true).FirstOrDefault();。目前您的 Controls.Find 返回一个 Control 数组
标签: c# winforms devexpress