目前,我正在尝试使用 Windows 窗体显示图表,该图表在 X 轴上显示月度数据,在 Y 轴上显示整数值;但是,我没有正确设置 X 轴的范围,其中 MonthYear 是 DateTime:
var pnChart = new System.Windows.Forms.Panel();
pnChart.Controls.Clear();
DataTable dtChartData = myDatabaseLayer.BuildDataTable("SELECT Added, Modified FROM tblStatistics WHERE ApplicationID = " + intApplicationID + " ORDER BY MonthYear");
Chart chart = GenerateChart(dtChartData, pnChart.Width, pnChart.Height, "ActiveBorder", 6);
chart.Series[0].XValueType = ChartValueType.DateTime;
chart.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd";
chart.ChartAreas[0].AxisX.Interval = 1;
chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Months;
chart.ChartAreas[0].AxisX.IntervalOffset = 1;
pnChart.Controls.Add(chart);
问题是,当图表显示时,X 轴的日期时间为“1900-01-01”所以我的问题是,如何将日期范围设置为从 2013-01-01 开始?
请注意,我已经搜索了互联网并尝试了以下设置,但它们没有给我正确的范围:
chart.ChartAreas[0].AxisX.Maximum = DateTime.Now.Ticks;
或者,
chart.ChartAreas[0].AxisX.Crossing = DateTime.Now.Ticks;
或者,
chart.ChartAreas[0].AxisX.Minimum = DateTime.Now.Ticks;
TIA。
更新: 请注意,我找到了如何使用这个正确设置范围:
chart.Series[0].XValueType = ChartValueType.DateTime;
DateTime minDate = new DateTime(2013, 01, 01);
DateTime maxDate = DateTime.Now;
chart.ChartAreas[0].AxisX.Minimum = minDate.ToOADate();
chart.ChartAreas[0].AxisX.Maximum = maxDate.ToOADate();
上面的代码现在为 X 轴设置了合适的范围;但是,现在图表本身是空白的。
更新 2:
是的,谢谢你 DasKrumelmonster——修复了它!我正在使用来自http://www.codeproject.com/Articles/168056/Windows-Charting-Application的代码,并且应该更仔细地查看作者受保护的内部 Chart GenerateChart(DataTable dtChartDataSource, int width, int height, string bgColor, int intType) 函数。为了纠正这个问题,我改变了这些行:
foreach (DataRow dr in dtChartDataSource.Rows)
{
double dataPoint = 0;
double.TryParse(dr[dc.ColumnName].ToString(), out dataPoint);
DataPoint objDataPoint = new DataPoint() { AxisLabel = "series", YValues = new double[] { dataPoint } };
chart.Series[series].Points.Add(dataPoint);
}
对此:
DateTime dtStart = new DateTime(2013, 01, 01);
int intMonthCounter = 0;
//Add data points to the series
foreach (DataRow dr in dtChartDataSource.Rows)
{
double dataPoint = 0;
double.TryParse(dr[dc.ColumnName].ToString(), out dataPoint);
DataPoint objDataPoint = new DataPoint() { AxisLabel = "series", YValues = new double[] { dataPoint } };
chart.Series[series].Points.AddXY(dtStart.AddMonths(intMonthCounter), dataPoint);
intMonthCounter++;
}
谢谢!