Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my list return only last row?

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.


1 Answers

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.

like image 171
David Avatar answered Mar 18 '26 06:03

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!