user3518032
user3518032

Reputation: 423

Returning list of items

I am retrieving multiple records from database and storing it in list. I have created properties class and then i assign data being retrieved to variables in properties and then trying to return all collection of values to client who made function call but it doesn't work. Why ? please make it correct.

Code:

 public Properties FetchCoordinates(String FetchParam) 
    {
        String[] parts = FetchParam.Split(',');
        sqlCom.CommandText = "FetchCoordinates";
        sqlCom.CommandType = CommandType.StoredProcedure;

        sqlCom.Parameters.Add("@IMEI", SqlDbType.VarChar).Value = parts[0].ToString();
        sqlCom.Parameters.Add("@DateTimeFrom", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[1].ToString());
        sqlCom.Parameters.Add("@DateTimeTo", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[2].ToString());
        SqlParameter sqlParam = new SqlParameter("@result", SqlDbType.Int);
        sqlCom.Parameters.Add(sqlParam);
        sqlCom.Parameters["@result"].Direction = ParameterDirection.Output;
        List<Properties> props = new List<Properties>();
        Properties p;

        try
        {
            sqlCon.Open();
            using (SqlDataReader reader = sqlCom.ExecuteReader())
{
            while (reader.Read())
            {
                p = new Properties()
                {
                    Longitude = reader["Longitude"].ToString(),
                    Latitude  = reader["Latitude"].ToString()
                };
                props.Add(p);
                return p;
            }

}



        }



        catch (Exception ex)
        {



        }

        finally
        {
            sqlCon.Close();
        }

    }

}

Properties.cs

public class Properties
{
    public Properties()
    {
    }

    public string Longitude { get; set; }
    public string Latitude { get; set; }

}

Upvotes: 0

Views: 70

Answers (1)

Kinexus
Kinexus

Reputation: 12904

Change the method signature;

public List<Properties> FetchCoordinates(String FetchParam) 

and rather than returning p which is only a single instance, return the List props;

 while (reader.Read())
            {
                p = new Properties()
                {
                    Longitude = reader["Longitude"].ToString(),
                    Latitude  = reader["Latitude"].ToString()
                };
                props.Add(p);

            }

 return props;

Upvotes: 4

Related Questions