weird result with c# winForms array of Lists
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"].ToStr开发者_如何学Cing();
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?
It looks like you are reusing the same MedicationTimelineClass object inside your loop. Remember that your class is a reference type. You are basically adding the same reference to your list and updating the values of the properties stored in the object at that reference. Ultimately, all of the "items" in your list refer to the same object.
Instantiate a new MedicationTimelineClass object with each iteration and then add that new object to your list.
In the "while (rdr.Read())" loop, you're just adding the same object (medObject) to the list each time. The list is being populated with the same object, over and over again.
精彩评论