Reputation:
I am using a list and filling it from the database.
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
Stories st = new Stories();
while (dt.Read())
{
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
}
list.Add(st);
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}
Stories model has only 2 properties such as Story, Image.
but my list returns only last row, why? I want it to return all rows.
Upvotes: 2
Views: 486
Reputation: 797
Add list inside the while:
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
Stories st;
while (dt.Read())
{
st= new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}
Since having list outside the while will add only last stored values
Upvotes: 0
Reputation: 1632
The Issue here is your "Add" method is placed after the while loop has finished executing.
public List<HimHer.Models.Stories> GetAllImages()
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
SqlCommand sqlcom = new SqlCommand("Select * from Images", con);
SqlDataAdapter adp = new SqlDataAdapter(sqlcom);
con.Open();
SqlDataReader dt = sqlcom.ExecuteReader();
List<HimHer.Models.Stories> list = new List<Stories>();
while (dt.Read())
{
Stories st = new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
return list;
}
}
catch (Exception ex)
{
throw ex;
}
}
Upvotes: 0
Reputation: 218837
Because you only ever add one element to the list:
Stories st = new Stories();
while (dt.Read())
{
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
}
list.Add(st);
Instead, add every element to the list:
while (dt.Read())
{
Stories st = new Stories();
st.Image = dt["Image"].ToString();
st.Story = dt["Story"].ToString();
list.Add(st);
}
Side note: Your catch
block is superfluous and actually detrimental to exception handling and debugging. You should just remove it entirely.
Upvotes: 9