weird result with c# winForms array of Lists

Posted by jello on Stack Overflow See other posts from Stack Overflow or by jello
Published on 2010-03-29T03:29:35Z Indexed on 2010/03/29 3:33 UTC
Read the original article Hit count: 528

Filed under:
|
|
|

so I'm trying to store values in an array of Lists in C# winForms. In the for loop in which I make the sql statment, everything works fine: the message box outputs a different medication name each time.

for (int i = 0; i < numberOfMeds; i++)
{

 queryStr = "select * from biological where medication_name = '" + med_names[i] + "' and patient_id = " + patientID.patient_id;

 using (var conn = new SqlConnection(connStr))
 using (var cmd = new SqlCommand(queryStr, conn))
 {
  conn.Open();

  using (SqlDataReader rdr = cmd.ExecuteReader())
  {
   while (rdr.Read())
   {
    medObject.medication_date = (DateTime)rdr["patient_history_date_bio"];
    medObject.medication_name = rdr["medication_name"].ToString();
    medObject.medication_dose = Convert.ToInt32(rdr["medication_dose"]);

    medsList[i].Add(medObject);

   }
  }
  conn.Close();

  MedicationTimelineClass medObjectx = medsList[i][0] as MedicationTimelineClass;
  MessageBox.Show(medObjectx.medication_name);
 }
}

but then, when I take the message box code out of the loop, meaning that the array of Lists is supposed to be populated, I always get the same value: the last value entered. the same medication name, no matter what number I put between those brackets. It's like if the whole array of Lists is populated with the same data.

for (int i = 0; i < numberOfMeds; i++)
{

 queryStr = "select * from biological where medication_name = '" + med_names[i] + "' and patient_id = " + patientID.patient_id;

 using (var conn = new SqlConnection(connStr))
 using (var cmd = new SqlCommand(queryStr, conn))
 {
  conn.Open();

  using (SqlDataReader rdr = cmd.ExecuteReader())
  {
   while (rdr.Read())
   {
    medObject.medication_date = (DateTime)rdr["patient_history_date_bio"];
    medObject.medication_name = rdr["medication_name"].ToString();
    medObject.medication_dose = Convert.ToInt32(rdr["medication_dose"]);

    medsList[i].Add(medObject);

   }
  }
  conn.Close();


 }
}

MedicationTimelineClass medObjectx = medsList[0][0] as MedicationTimelineClass;
MessageBox.Show(medObjectx.medication_name);

what's going on here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms