我有一个SQL数据库,该数据库存储一些我想绘制的数据。问题是,我继承了此数据库,并且它们将datetime值存储为Ticks。当我将图表数据源设置为此表时,它似乎无法理解刻度线。
如何获取图表以将刻度线转换回图表可以理解的DateTime格式?
我的SQL查询和代码:
static public DataTable get_I1(RunningTests rt)
{
DataTable dt = new DataTable();
using (SqlConnection cs = new SqlConnection(connString))
{
string query = string.Format("SELECT Time_Stamp, I1 FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp >= '{1}' AND Time_Stamp <= '{2}'", rt.Unit_ID, rt.StartTime.Ticks, rt.StopTime.Ticks);
Console.WriteLine(query);
SqlCommand cmd = new SqlCommand(query, cs);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
dt.DefaultView.Sort = "Time_Stamp DESC";
dt = dt.DefaultView.ToTable();
return dt;
}
用于设置图表数据源的代码:
private void do_chart_I1(RunningTests rt)
{
muCalGUI1.chartI1.Series.Clear();
DataTable dt = SQL.get_I1(rt);
muCalGUI1.chartI1.DataSource = dt;
Series s = new Series("I1");
s.XValueMember = "Time_Stamp";
s.YValueMembers = "I1";
s.ChartType = SeriesChartType.Line;
s.BorderWidth = 2;
s.MarkerSize = 5;
s.MarkerStyle = MarkerStyle.Circle;
muCalGUI1.chartI1.ChartAreas[0].AxisY.IsStartedFromZero = false;
muCalGUI1.chartI1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd\nHH:mm:ss";
muCalGUI1.chartI1.ChartAreas[0].AxisY.LabelStyle.Format = "0";
muCalGUI1.chartI1.ChartAreas[0].RecalculateAxesScale();
muCalGUI1.chartI1.Series.Add(s);
muCalGUI1.chartI1.Legends.Clear();
}
答案 0 :(得分:0)
我有一个可行的解决方案。如果有人可以提供“更干净”的方法,我很乐意将其标记为答案。现在,我的工作是创建一个新的数据表并将刻度线转换为日期时间。
SQL代码:
static public DataTable get_I1(RunningTests rt)
{
DataTable dt = new DataTable();
using (SqlConnection cs = new SqlConnection(connString))
{
//string query = string.Format("Select TOP {0} Serial AS [Serial #], Start, [Stop], N, ROUND(Mean,4) AS Mean, ROUND(StdDev,4) AS [Standard Deviation], ROUND(Minimum,4) AS Min, ROUND(Maximum,4) AS Max FROM TestTime JOIN Membrane ON TestTime.Membrane_ID = Membrane.Membrane_ID WHERE Serial LIKE '{1}' ORDER BY TestTime_ID", numRecords, serial);
string query = string.Format("SELECT Time_Stamp, I1 FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp >= '{1}' AND Time_Stamp <= '{2}'", rt.Unit_ID, rt.StartTime.Ticks, rt.StopTime.Ticks);
SqlCommand cmd = new SqlCommand(query, cs);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
//Previous user stored the date time as ticks, have to convert back to DateTime
DataTable dtCloned = new DataTable();
dtCloned.Clear();
dtCloned.Columns.Add("Time_Stamp", typeof(DateTime));
dtCloned.Columns.Add("I1", typeof(int));
foreach (DataRow dr in dt.Rows)
{
DataRow r = dtCloned.NewRow();
r[0] = new DateTime((long)dr[0]);
r[1] = dr[1];
dtCloned.Rows.Add(r);
}
dtCloned.DefaultView.Sort = "Time_Stamp DESC";
dtCloned = dtCloned.DefaultView.ToTable();
return dtCloned;
}