Jimmy Live
Jimmy Live

Reputation: 271

Regarding overwriting data in a while loop

I'm having a problem outputting to a WebGrid because my list gets overwritten, so by the end, I have the final line of data written for every line on the grid. I have to use a while loop because the data is continually being added to, and we're looking at alot of data, so I'm trying not to write to another list.

public class ChemData
{
    string strSQLconnection = "Server=Server;Database=data;Uid=Username;Pwd=Password";

    public int productId { get; set; }
    public string productName { get; set; }

    public List<ProdData> ProdList = new List<ProdData>();

    public List<ProdData> ProdDataPull()
    {
        ProdData Analysis = new ProdData();
        SqlDataReader reader = null;
        SqlConnection conn = new SqlConnection(strSQLconnection);
        SqlCommand query = new SqlCommand("Select * from producttable");

        conn.Open();
        query.Connection = new SqlConnection(strSQLconnection);
        query.Connection.Open();
        reader = query.ExecuteReader();
        while (reader.Read())
        {
            if (!reader.IsDBNull(0)) Analysis.productId = reader.GetInt32(0);
            if (!reader.IsDBNull(1)) Analysis.productName = reader.GetString(1);

            ProdList.Add(Analysis);
         } 
         return ChemList;
   } 
 }

Upvotes: 1

Views: 228

Answers (1)

J...
J...

Reputation: 31433

This is because Analysis is created only once. Adding it to the list each time adds a reference to the same object. Moving the creation to inside the while loop should fix this

while (reader.Read())
{
    ProdData Analysis = new ProdData();
    if (!reader.IsDBNull(0)) Analysis.productId = reader.GetInt32(0);
    if (!reader.IsDBNull(1)) Analysis.productName = reader.GetString(1);

    ProdList.Add(Analysis);
}

This creates a new ProdData object on each iteration of the loop and assigns it to Analysis, then updates its contents and adds that reference to the list.

With the creation of Analysis outside the loop Analysis continues to point to the same ProdData object that gets added over and over to the list while its values are overwritten each time.

See : Reference Types vs. Value Types

Upvotes: 2

Related Questions