Mussammil
Mussammil

Reputation: 894

list values changes when dataset iteration

I have List of type Date_Check ,I execute a sql query and retrieve the values in a dataset and I populate the List by iterate through the dataset ,the problem is that when the second iteration towards the list[0],list[1],list[2]... values got the replaced by current object values

Here is my code :

 string query = "select Record_Id, Movie_Name from tbl_theater_master ";
 DataSet dtst_Theatrs = new DataSet();
 dtst_Theatrs = ObjCommon.GetObject.ExecuteQuery_Select(Connection.ConnectionString, query);

 if (dtst_Theatrs.Tables[0].Rows.Count != 0)
 {
   List<Date_Check> lst_Date_Check = new List<Date_Check>();
   Date_Check obj_Date_Check = new Date_Check();

   for (int i = 0; dtst_Theatrs.Tables[0].Rows.Count > i; i++)
   {
        obj_Date_Check.Movie_Name = dtst_Theatrs.Tables[0].Rows[i]["Movie_Name"].ToString();
        obj_Date_Check.Record_Id = dtst_Theatrs.Tables[0].Rows[i]["Record_Id"].ToString();
         lst_Date_Check.Add(obj_Date_Check);
   }
 }

Here is my Date_Check object :

 public class Date_Check
{
    public string Record_Id { get; set; }
    public string Movie_Name { get; set; }
}

When dataset iteration is completed the lst_Date_Check got all the indexes changed to the Last iterations values ,what's wrong with my code

Upvotes: 0

Views: 51

Answers (2)

Chris Morledge
Chris Morledge

Reputation: 71

This is because your Date_Check object is a reference type and not a value type. This means the line Date_Check obj_Date_Check = new Date_Check(); creates the variable in memory once and from then on every time update that object you are updating the same single object. You have 2 options:

Instantiate the object inside the for loop to create a single object in memory to work with i.e:

for (int i = 0; dtst_Theatrs.Tables[0].Rows.Count > i; i++)
   {
        Date_Check obj_Date_Check = new Date_Check();
        obj_Date_Check.Movie_Name = dtst_Theatrs.Tables[0].Rows[i]["Movie_Name"].ToString();
        obj_Date_Check.Record_Id = dtst_Theatrs.Tables[0].Rows[i]["Record_Id"].ToString();
         lst_Date_Check.Add(obj_Date_Check);
   }

Or create your Date_Check object as a Value Type by using a Struct i.e:

public struct Date_Check
{
    public string Record_Id { get; set; }
    public string Movie_Name { get; set; }
}

Upvotes: 0

Hassan
Hassan

Reputation: 5430

Keep creation of the object of the class Date_Check obj_Date_Check = new Date_Check(); inside the for-loop. That's how you make new object on every iteration.

for (int i = 0; dtst_Theatrs.Tables[0].Rows.Count > i; i++)
{
     Date_Check obj_Date_Check = new Date_Check();
     obj_Date_Check.Movie_Name = dtst_Theatrs.Tables[0].Rows[i]["Movie_Name"].ToString();
     obj_Date_Check.Record_Id = dtst_Theatrs.Tables[0].Rows[i]["Record_Id"].ToString();
     lst_Date_Check.Add(obj_Date_Check);
}

Upvotes: 1

Related Questions