'How to Populate DataTable in Loop and Add to DataSet
I am trying to loop through a bunch of data and grab data for certain locations and put it into a DataTable. Then put the DataTable for that location into a DataSet and the DataSet is returned. The number of locations can vary, so I wanted to loop through. I am getting an error that the table already exists since I'm trying to reuse the DataTable. Do I need to redo the table in each loop and dispose it before it loops again?
DataTable compResults = new();
TestResults.DataSetName = "Inventory Audit";
DataRow workrow;
// Builds Compare Result Table
if (compResults.Columns.Count == 0)
{
DataColumn dc = compResults.Columns.Add("ID", typeof(Int32));
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
compResults.Columns.Add("Location");
compResults.Columns.Add("SKU");
compResults.Columns.Add("System");
compResults.PrimaryKey = new DataColumn[] { compResults.Columns["ID"] };
}
foreach (DataRow SearchLocation in pplFacilities.Rows)
{
int intSearch = Int32.Parse(SearchLocation["location_id"].ToString());
string mrg_location = SearchLocation["location_id"].ToString();
string ppl_owner = SearchLocation["owner"].ToString();
// Names the Table the Location Name
compResults.TableName = tName.ToString();
// Searches ppl Table for Items with the selected location
// Results stored in pplLocSearchRows
string pplLocSearchExpression = $"storerkey = '{ppl_owner}'";
string pplLocSortExpression = $"SKU ASC";
DataRow[] pplLocSearchRows = _pplapi.pplResult.Select(pplLocSearchExpression, pplLocSortExpression);
// Searches mrg Table by location_id and item_id
foreach (DataRow pplRow in pplLocSearchRows)
{
string mrgLocSearchExpression = $"location_id = '{mrg_location}' and item_id = '{pplRow["SKU"]}'";
string mrgLocSortExpression = $"item_id ASC";
DataRow[] mrgLocSearchRows = _mrgapi.apiResult.Select(mrgLocSearchExpression, mrgLocSortExpression);
foreach (DataRow mrgRow in mrgLocSearchRows)
{
// Compare pplRow and mrgRow
// If Anything Doesn't Match add ppl and mrg to CompTable
if (pplQty != mrgQty)
{
workrow = compResults.NewRow();
workrow["Location"] = ppl_owner;
workrow["SKU"] = pplRow["sku"];
workrow["System"] = "ppl";
compResults.Rows.Add(workrow);
}
}
}
Console.WriteLine($"TableName: {compResults.TableName}");
// Puts the Compare Tables into TestResults DataSet
TestResults.Tables.Add(compResults);
// Clears DataTable so the next location can be entered.
compResults.Clear();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
