Reputation: 89
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.
Upvotes: 2
Views: 41995
Reputation: 4465
Note: if we have column of type DateTime in DataBase and String in asp.net core/Csharp application
we can convert DateTime to string at store procedure level as
e.g
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
Full example of Store procedure
SELECT referralCostsID,
ClientID,
ReferralSource,
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
AdCost,
Notes
FROM referralcostssetup
Upvotes: 0
Reputation: 87
Use
if (Convert.IsDBNull(columnValue))
{
return null;
}
return columnValue;
Ever validate is data is null or emty and return a value
Upvotes: -1
Reputation: 48558
Do
list.Add(Convert.ToString(myReader["Date"]));
It seems your Date
column is not string but a datetime column.
Doing (string)myReader["Date"]
tries explicit typecasting on a datetime column to string which is not possible. But Convert.ToString
gives the string representation of your value.
Even if the value is null
, Convert.ToString(object value)
will return null
instead of throwing exception like .ToString()
.
Upvotes: 2
Reputation: 14024
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
Upvotes: 9