Search code examples
c#listobjectdatatablefill

DataTable fill Object


I'm coding in C# but there is an error I actually can't solve, maybe can someone help me here!

Sorry for my english, I'm not a native speaker!

Here is my code :

public List<Materiel> GetAllTubas()
{
 DataAccess.Oradb getListTubas = new DataAccess.Oradb();
 getListTubas.GetTubaDatabase(null);

 List<Materiel> ListMateriel = new List<Materiel>(); 

 foreach(DataRow row in dt.Rows)  //the name "dt" does not exist in the current context     {
    var myListTuba = new Materiel();
    myListTuba.Nom = row["nom_tuba"];
    ListMateriel.Add(myListTuba);
 }

 return ListMateriel;
}

In this methode I call another method GetTubaDatabase ; connect to database and SQL query, it returns me DataTable dt fill with the result of my query. Now I would like to create a List thanks to my Datatable, but an error appear : the name "dt" does not exist in the current context (approximately translate from my mothertongue)

I think that's not a huge error but I can't solve it and dunno how I can.

Hope you'll help me !

Thanks a lot !


Solution

  • You need to first assign the return value to a variable:

    DataTable dt = getListTubas.GetTubaDatabase(null);
    

    Then you can use it later in your code. Executing a method does not magically create variables.