zaria khan zaria khan - 1 year ago 68
C# Question

Adding items to list from DataRow

I have following code to copy DataTable rows into my Object. But it overwrites previously added list items each time with the new row. What is wrong with my code?

DataTable dt = GetDataTableByIndex(data, 1);
if (dt != null && dt.Rows.Count > 0)
{
if (dt != null && dt.Rows.Count > 0)
{
providerQualification.ProviderDetails = new List<ProviderDetail>();
ProviderDetail providerDetail = new ProviderDetail();
foreach (DataRow row in dt.Rows)
{
providerDetail.ProviderName = row["Provider Name"].ToString();
providerDetail.QualificationTime = row["Qualify Time (Sec.)"].ToString();
providerDetail.ServiceableOffers = row["Total Serviceable Offers"].ToString();
providerQualification.ProviderDetails.Add(providerDetail);
}
}
}

Answer Source

Try this,

DataTable dt = GetDataTableByIndex(data, 1);
if (dt != null && dt.Rows.Count > 0)
{
      providerQualification.ProviderDetails = new List<ProviderDetail>();
      ProviderDetail providerDetail;
      foreach (DataRow row in dt.Rows)
      {    
          providerDetail = new ProviderDetail();
          providerDetail.ProviderName = row["Provider Name"].ToString();
          providerDetail.QualificationTime = row["Qualify Time (Sec.)"].ToString();
          providerDetail.ServiceableOffers = row["Total Serviceable Offers"].ToString();
          providerQualification.ProviderDetails.Add(providerDetail);
      }
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download