1

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

  • 2
    `Friends` is a class, which is a reference type. The `friend` variable holds a reference to the 1 `Friends` object you have created, you modify this object multiple times and add it to the list, but you only have 1 object, with multiple references. Instead. move this line: `Friends friend = new Friends();` inside the loop as well, that way you will create 1 object per iteration. – Lasse V. Karlsen May 29 '19 at 07:16
  • 1
    You are adding your object, then changing its fields, so at the end, all will be same last fields. – SᴇM May 29 '19 at 07:16
  • Adding a class instance to the list doesn't create a copy, it only adds a reference to that instance. The loop keeps modifying the same object and adding references to it in the list – Panagiotis Kanavos May 29 '19 at 07:21
  • thanks lasse , and all – AdityaUbale May 29 '19 at 07:25

2 Answers2

2

You need to instantiate Friends object inside for loop.

In your case you are creating instance of Friends object outside for loop and changing values of its property in every iteration, that is why every time your code ending up with same instance in the list.

You need to create new instance of Friends everytime, assigning values to its property everytime and adding it to list in every iteration

    for (var i = 0; i < dt.Rows.Count; i++)
    {
        Friends friend = new Friends();  // Change scope of friends from function level to for loop level.
        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);
    }
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

You are changing the same friend object over and over again.

Although the properties change every time, it's still the same object reference.

This should work:

public ViewResult Contact()
{
    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++)
    {

        Friends friend = new Friends();
        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);
}

See Here to see more on reference types.

Additionally, some more coding tips:

  1. Name your classes in singular, a single Friends object is not actually friends, it's a Friend
  2. Name properties like FirstName, LastName etc. instead of firstName lastName. This is just a generally accepted convention.
Alen Genzić
  • 1,398
  • 10
  • 17