I have this code in my gymInfo class:
public class gymInfo
{
public gymArray getAllGymsByStars()
{
gymDataTableAdapters.gymsTableAdapter gymsTableAdapter = new gymDataTableAdapters.gymsTableAdapter();
DataTable gymsDataTable = gymsTableAdapter.getAllGymsByStars();
gymArray gymArray = new gymArray();
foreach(DataRow row in gymsDataTable.Rows)
{
gymArray.name = row["name"].ToString();
}
return gymArray;
}
}
The gymsDataTable
contains 20 rows of names, now I have made a custom class, here is the code:
public class gymArray
{
public string name { get; set; }
}
Which I expected the string name
to get populated with 20 names (as their is 20 rows in the datatable) however when I debug on line return gymArray
it only shows the name of the last row rather than showing a whole custom array of names.
Does anyone understand what I'm doing wrong?
You haven't actually created an array. You've got a single gymArray
object, and you're just changing its name property repeatedly.
Also, you're not following C# conventions when naming things. Your code should be more like this:
public class GymInfo
{
public List<Gym> GetAllGymsByStars()
{
gymDataTableAdapters.gymsTableAdapter gymsTableAdapter = new gymDataTableAdapters.gymsTableAdapter();
DataTable gymsDataTable = gymsTableAdapter.getAllGymsByStars();
List<Gym> gyms = new List<Gym>();
foreach(DataRow row in gymsDataTable.Rows)
{
Gym gym = new Gym();
gym.Name = row["name"].ToString();
gyms.Add(gym);
}
return gyms;
}
}
public class Gym
{
public string Name { get; set; }
}
Instead of a naming a single object an "array", I created a generic List of Gym objects and returned that from the GetAllGymsByStars
method.