我在C#中创建了一个与捐赠数据相关联的图表。每周,捐赠总额都记录在表格中。图表将这些数字拉出并以折线图形式绘制。
我遇到的问题是,每周都会记录为一周中的某一天,因此基于周工作的控件无法正常工作。我附上了我的代码和下面结果的图片。
我想知道为什么这里的每个数据点都显示为一周中的某一天。我是如何加载数据的?
感谢您提供任何帮助。
这是我的代码:
#region Chart4
string DonationSelect = this.DonationSelect.SelectedValue;
Time = Convert.ToInt32(DonationSelect);
if (Time > 3)
Chart4.Series[0].IsValueShownAsLabel = false;
else
Chart4.Series[0].IsValueShownAsLabel = true;
Chart4.Series[0].ChartType = SeriesChartType.Line;
Chart4.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;
StartDate = GetNextDay(DateTime.Today, DayOfWeek.Sunday);
TargetDate = GetNextDay(StartDate.AddMonths(-1 * Time), DayOfWeek.Sunday);
for (DateTime i = TargetDate; i <= DateTime.Now; i = i.AddDays(7))
{
int Donations = 0;
var oDonation = oDatabase.ExecuteScalar(@"SELECT Offering FROM
tblStats WHERE Date=@Date",
"Date", i);
if (oDonation != null && oDonation != DBNull.Value)
{
Donations = Convert.ToInt32(oDonation);
}
//int Attendance = Convert.ToInt32();
string Date = i.ToShortDateString();
Chart4.Series[0].Points.AddXY(Date, Donations);
}
StripLine StripLine = new StripLine();
StripLine.BackColor = Color.LightGray;
StripLine.Interval = 1;
StripLine.IntervalType = DateTimeIntervalType.Weeks;
StripLine.StripWidth = .5;
StripLine.StripWidthType = DateTimeIntervalType.Weeks;
StripLine.IntervalOffset = 0;
StripLine.IntervalOffsetType = DateTimeIntervalType.Days;
Chart4.Legends.Add(new Legend("Legend3"));
Chart4.Series[0].Legend = "Legend3";
Chart4.Series[0].IsVisibleInLegend = true;
Chart4.Series[0].LegendText = "Donations";
Chart4.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
Chart4.BackColor = Color.PowderBlue;
Chart4.Series[0].BorderWidth = 3;
Chart4.Series[0].BorderColor = Color.Orange;
Chart4.ChartAreas["ChartArea1"].AxisX.Title = "Date";
Chart4.ChartAreas["ChartArea1"].BackColor = Color.LightGray;
Chart4.ChartAreas["ChartArea1"].BackSecondaryColor = Color.White;
Chart4.ChartAreas["ChartArea1"].BackGradientStyle = GradientStyle.TopBottom;
Chart4.ChartAreas["ChartArea1"].AxisX.StripLines.Add(StripLine);
#endregion
答案 0 :(得分:1)
根据http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx,您可以尝试替换这些行:
string Date = i.ToShortDateString();
Chart4.Series[0].Points.AddXY(Date, Donations);
与那些:
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;
Chart4.Series[0].Points.AddXY(cal.GetWeekOfYear(i, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek), Donations);
答案 1 :(得分:1)
好的,所以我昨天更多地摆弄了它,这就是问题所在: string Date = i.ToShortDateString();
Chart4.Series[0].Points.AddXY(Date, Donations);
问题在于,为了使日期正常工作,需要将它们作为DateTime
变量而不是字符串添加到轴中。因此,任何与周工作的事情都只能以7个字符串为单位计算。
正确的代码在这里:
Chart4.Series[0].Points.AddXY(i, Donations);
感谢您指出我正确的方向!