2011-04-14 622 views
0

我想插入產品詳情數組列表中的產品的ArrayList數組列表存儲到在c#另一個數組列表

ArrayList的產品=新的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); 
    } 

但在產品列表中的每個entery充滿了最後的產品詳細的ArrayList。 我在這裏做什麼錯?

+0

什麼'myTable.Rows.IndexOf(myRow )每次迭代返回? – khachik 2011-04-14 11:40:55

+0

它返回foreach循環的索引。 – 2011-04-14 11:41:36

+0

你想添加ArrayList作爲一個整體還是其最後一個項目?你可以更清楚你正在試圖做 – w69rdy 2011-04-14 11:41:58

回答

1

嘗試移動

ArrayList productDetail = new ArrayList(); 

foreach循環中:

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); 
} 

的一點是,在你的代碼,你一直在增加對同一個對象的引用:Insert是不要每次都複製你的清單...

1

productDetails只有一個項目在裏面。 您的第一步是productDetail.Clear(); 移到foreach外部以獲得您想要的結果。

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); 
     } 
+1

但仍然,產品中的所有條目將包含相同的東西... – 2011-04-14 11:45:26

相關問題