I want to return list of records using stored procedure and datareader in C#. Currently, it is giving me error
Cannot implicitly convert type 'ClsHorseTracker' to 'System.Collections.Generic.List'
Code:
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker = new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
};
}
}
}
return clsHorseTracker;
}
clsHorseTracker is a list of ClsHorseTracker. So you need to add new object to the list in "while" loop instead of assign an object to the list Try this
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL;
sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker.Add(new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
});
}
}
}
return clsHorseTracker;
}