I have 5 records in db , and i want to show them on UI , but with the below code while iterating it shows different object but in list it shows same object 5 times Help me with this and tell if i can have better coding practice
I have used For loop to iterate and get the record into list of friend
public ViewResult Contact()
{
Friends friend = new Friends();
List<Friends> friends = new List<Friends>();
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from Friends", con);
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
for (var i = 0; i < dt.Rows.Count; i++)
{
friend.friendId = Convert.ToInt32(dt.Rows[i]["FriendId"]);
friend.firstName = dt.Rows[i]["FirstName"].ToString();
friend.lastName = dt.Rows[i]["LastName"].ToString();
friend.currentAmountGiven = Convert.ToInt32(dt.Rows[i]["CurrentAmountGiven"]);
friend.totalAmount = Convert.ToInt32(dt.Rows[i]["TotalAmount"]);
friends.Add(friend);
}
return View(friends);
}
In Friends i am getting same row 5 times from db
need output as i told above