Reputation: 15963
I want to insert productDetail arraylist in products arraylist
ArrayList products = new ArrayList();
ArrayList productDetail = new ArrayList();
foreach (DataRow myRow in myTable.Rows) { productDetail.Clear(); productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString()); products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail); }
But each entery in product list is filled with last productdetails ArrayList. What wrong I am doing here?
Upvotes: 0
Views: 547
Reputation: 57202
Try moving
ArrayList productDetail = new ArrayList();
inside the foreach
loop:
ArrayList products = new ArrayList();
foreach (DataRow myRow in myTable.Rows) {
ArrayList productDetail = new ArrayList();
productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString());
products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail);
}
The point is that, in your code, you are always adding a reference to the same object: Insert
is not making a copy of your list each time...
Upvotes: 1
Reputation: 5084
productDetails only ever has one item in it.
Your first step is productDetail.Clear();
Move that outside the foreach to achieve your desired result.
ArrayList products = new ArrayList();
ArrayList productDetail = new ArrayList();
productDetail.Clear();
foreach (DataRow myRow in myTable.Rows)
{
productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString());
products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail);
}
Upvotes: 1