Search code examples
c#mysqllivecharts

Unable to cast object of type 'System.DateTime' to type 'System.String'. c#


I'm trying to display the dates and restored it to the Labels = strings, but I got an error on line list.Add((string)myReader["Date"]);

Here's my code:

con.Open();
myReader = cmdDB.ExecuteReader();
List<string> list = new List<string>();
while (myReader.Read())
{
    list.Add((string)myReader["Date"]);
}

string[] strings = list.Select(x => x.ToString()).ToArray();
cartesianChart1.AxisX.Add(new Axis
{
    Title = "Date",
    Labels = strings
});

cartesianChart1.AxisY.Add(new Axis
{
    Title = "Sales",
    LabelFormatter = value => value.ToString()
});

Any solution? Thank you! P.S. I'm using LiveCharts and MySQL.


Solution

  • You can try like this

    list.Add(myReader["Date"].ToString());
    

    If you want you can also apply formatting to your date in the ToString(dd-MM-yyyy) using Custom Date and Time Format Strings