简体   繁体   中英

Reading the average value from MySql Database. C# ASP.NET

I have this codes in my page:

protected void Page_Load(object sender, EventArgs e)
{
    conn.Open();
    string selectQuery = @"SELECT AVG(odometer_reading),truck_id FROM 
              inspection WHERE date BETWEEN '2015-12-01' AND '2016-06-01' 
              GROUP BY truck_id";
    MySqlCommand cmd = new MySqlCommand(selectQuery, conn);
    MySqlDataReader reader = cmd.ExecuteReader();
    foreach (DbDataRecord rowData in reader) 
    {
       populateTable(rowData);
    }               
}
private void populateTable (DbDataRecord rowData)
{
    TableRow tr = new TableRow();
    TableCell cell1 = new TableCell();
    cell1.Text = rowData.GetString(rowData.GetOrdinal("AVG(odometer_reading)")).ToString();
    tr.Cells.Add(cell1);// Error
    TableCell cell2 = new TableCell();
    cell2.Text = rowData.GetString(rowData.GetOrdinal("truck_id")).ToString();
     tr.Cells.Add(cell2);
     tbl_TruckEfficiency.Rows.Add(tr);
 }

I am receiving an error of Unable to cast object of type 'System.Double' to type 'System.String'. What could be the cause of this.

Or

Is there other way to get the AVG(odometer_reading) to get it to cell1.text disregarding its datatype to avoid the error. Thanks!

试试这个

cell1.Text=rowData["AVG(odometer_reading)"].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM