Senn Alonzo Senn Alonzo -4 years ago 92
C# Question

Converting a DataTable to my List<T>

cmd.CommandText = sql;
SqliteDataReader rdr = cmd.ExecuteReader();
return dt;

DataTable tb = new DataTable();
List<Details> objList = new List<Details>

foreach (var obj in dt)
var item = new Details();
item.ID = obj.ID;
item.Dosage = obj.Dosage;
item.Drug = obj.Drug;
item.Patient = obj.Patient;
item.Date = obj.Date;


the idea is here but theres a error in dt in forceach(var obj in dt)

Answer Source

You have to

  1. Execute reader
  2. Read the coursor
  3. Create your class instances
  4. Collect these instances into a List<T>

Something like this

   // List which will be used to collect records from the query
   List<MyClass> list = new List<MyClass>();

   cmd.CommandText = sql;

   //DONE: execute reader; wrap IDisposable into using
   using (SqliteDataReader rdr = cmd.ExecuteReader()) {
     //DONE: read each cursor's record
     while (rdr.Read()) {
       //DONE: Turn each record into MyClass instance
       MyClass item = new MyClass();

       //TODO: Assign properties
       item.Property1 = Convert.ToString(rdr[0]);
       item.Property2 = Convert.ToInt32(rdr[1]); 

       //DONE: Finally, collect all the intances created into the list 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download