1

Hi I have a method which returns list but i'm getting un-desired results,please let me know what is wrong in below code.

cmd2.CommandText = "select * from Blogs order by id desc"; 
SqlDataReader reader = cmd2.ExecuteReader(); 
List<Blogs> blogslist = new List<Blogs>(); 
while (reader.Read()) 
{ 
   blog.Id = Convert.ToInt16(reader["id"]); 
   blog.email = reader["email"].ToString(); 
   blog.description = reader["description"].ToString(); 
   blog.date =Convert.ToDateTime(reader["date"]); 
   blogslist.Add(blog); 
}
2
  • 1
    What is the undesired result ? Error message What is it ? Wrong results ? What is it ? Empty list ? Wrong data in a specific column. Please update your answer and be specific. Commented Jul 29, 2016 at 5:26
  • Blogs table has 4 different records , after reader.read() the blogslist contains the same record 4 times instead of 4 different records . Commented Jul 29, 2016 at 5:32

1 Answer 1

3

Blog has been declared & instantiated outside of your reader.Read() statement, you are updating the same object reference each time around the loop which is why you are seeing repeating objects in your list.

cmd2.CommandText = "select * from Blogs order by id desc"; 
SqlDataReader reader = cmd2.ExecuteReader(); 
List<Blogs> blogslist = new List<Blogs>(); 
while (reader.Read()) 
{ 
   var blog = new Blogs();
   blog.Id = Convert.ToInt16(reader["id"]); 
   blog.email = reader["email"].ToString(); 
   blog.description = reader["description"].ToString(); 
   blog.date =Convert.ToDateTime(reader["date"]); 
   blogslist.Add(blog); 
}

Please mark this as your accepted answer if it solves your problem.

Sign up to request clarification or add additional context in comments.

3 Comments

He posted the code as plain text at first, that's what the <classType> part got removed somehow.
Thanks user3185569, that eliminates that part then.
Thanks a lot Michael :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.