0

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?

6
  • What does myTable.Rows.IndexOf(myRow) return on each iteration? Commented Apr 14, 2011 at 11:40
  • It returns the index of foreach loop. Commented Apr 14, 2011 at 11:41
  • You want to add the ArrayList as a whole or its last item? Can you be more clear about that you are trying to do Commented Apr 14, 2011 at 11:41
  • Try products.Add((object)productDetail); instead of Insert. Commented Apr 14, 2011 at 11:42
  • ArrayList is deprecated and shouldn't really be used if you can avoid it. Generics is useful here, in particular List<T>. Commented Apr 14, 2011 at 11:49

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.