[英]how to get date column of csv and use it as x-axis in a chart?
In my Windows forms application I'm trying to get a CSV file which as 2 columns.First for date and second for values.The problem is after I take my csv file I get an error.It says string was not recognized as a valid datetime. 在我的Windows窗体应用程序中,我尝试获取一个2列的CSV文件。第一个用于日期,第二个用于值。问题是在我获取csv文件后出现错误。它说字符串未被识别为有效约会时间。 Here is my code: 这是我的代码:
string dosyaAdi;
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
dosyaAdi = openFileDialog1.FileName;
}
var reader = new StreamReader(File.OpenRead(dosyaAdi));
List<string> zaman = new List<string>();
List<string> deger = new List<string>();
while (!reader.EndOfStream)
{
var satir = reader.ReadLine();
var degerler = satir.Split(',');
if (degerler.Count() > 1)
{
zaman.Add(degerler[0]);
deger.Add(degerler[1]);
}
}
MessageBox.Show("Zaman ve değer listelere atıldı");
chart1.Series["Series1"].XValueType = ChartValueType.Time;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "M-d-yyyy HH:mm:ss";
DateTime newdatetime = new DateTime();
for (int i = 0; i < zaman.Count; i++)
{
newdatetime = DateTime.ParseExact(zaman[i], "M-d-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
chart1.Series["Series1"].Points.AddXY(newdatetime.ToString("M-d-yyyy HH:mm:ss"));
}
for (int j = 0; j < deger.Count; j++)
{
chart1.Series["Series1"].Points.AddY(deger[j]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
any help would be much appreciated.Thank you 任何帮助将不胜感激。谢谢
You will want to use DateTime.ParseExact with a valid format string: 您将要使用带有效格式字符串的DateTime.ParseExact :
string toParse = "09/18/2014 23:15:08.170";
DateTime d = DateTime.ParseExact(toParse, "MM/dd/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);
with DateTime.ParseExact
the string to parse must match exactly the format provided... in your case, you should have. 使用DateTime.ParseExact
进行解析的字符串必须与提供的格式完全匹配...就您而言,您应该拥有。
"MM/dd/yyyy HH:mm:ss.fff"
THere's also Parse and TryParse, which would be a little more relaxed 还可以使用Parse和TryParse,这会更加轻松
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.