krishna mohan
krishna mohan

Reputation: 111

unble to convert data table to list in c#

i want to show datatable data into html for that im trieng to convert datatable to list. but getting erorr cannot implicitly convert type 'System.web.mvc.viewresult' to system.collection.genericlist

 public ViewResult Report_trans_consumption(DateTime? fromDate, DateTime? toDate)
        {
            ViewBag.fromDate = fromDate;
            ViewBag.toDate = toDate;
            List<Trans_energycons_ReportModel> model = null;
            using ("constr"))
            { 
                con.Open();
                SqlCommand cmd_get_transformer_consumption = new SqlCommand(@"SELECT 
    Date,units
    FROM [Total_Power]) desc", con);
                SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
                DataTable dt = new DataTable();
                da_get_trans_consumption.Fill(dt);
                Trans_energycons_ReportModel m =new Trans_energycons_ReportModel();
                foreach (DataRow row in dt.Rows)
                {
                    string deviceDate = row["Date"].ToString();
                    string units = row["Units"].ToString();
                    m.DeviceDate =Convert.ToDateTime(deviceDate);
                    m.Units =Convert.ToDouble(units);
                    model.Add(m);//getting error here
                }
            }
            return View(model); 
        }
    }

Model

  public class Trans_energycons_ReportModel
    {
        public DateTime DeviceDate { get; set; }
        public double Units { get; set; }

    }

Upvotes: 0

Views: 63

Answers (2)

Mohammed Sajid
Mohammed Sajid

Reputation: 4903

Change the List<Trans_energycons_ReportModel> to ViewResult or ActionResult, like the following code :

public ViewResult Report_trans_consumption(DateTime? fromDate, DateTime? toDate)
{
 ....
}

Upvotes: 1

dhrumil shah
dhrumil shah

Reputation: 82

Below line won't work

model = dt.AsEnumerable().ToList();

You have to manually map your properties from the data table, like

 foreach(DataRow row in dt.Rows)
 { 
     string deviceDate = row["DeviceDate"].ToString();
     string units = row["Units"].ToString();
     // convert your data and assign them in model and then use that model
 }

Edit:

Your return type is List<Trans_energycons_ReportModel>

so you should return return model; instead of return View(model);

Upvotes: 1

Related Questions