title: This Row Already Belongs To This Table
body: <p>I get an error 'this row already belongs to this table' from the following code:</p>
  
  <pre><code>public static DataTable AddNewAllocations(string pCaseNo, ref DataTable pTable)
      {
          try
          {
              string sqlText = "SELECT UserID FROM tblUsers;";
              aSqlQuery aQ = new aSqlQuery(sqlText, "table");
              DataTable userTable = aQ.TableResult;
  
              foreach (DataRow userRow in userTable.Rows)
              {
                  int allocAlready = 0;
                  foreach (DataRow allocRow in pTable.Rows)
                  {
                      if (allocRow["FeeEarner"].ToString() == userRow["UserID"].ToString())
                      {
                          allocAlready = 1;                            
                      }
                  }
                  if (allocAlready == 0)
                  {
                      string strUser = userRow["UserID"].ToString();          
                      decimal fees = cTimesheet.UserFees(strUser, pCaseNo);
                      int intCaseNo = Int32.Parse(pCaseNo);
                      if (fees &gt; 0)
                      {
                          Object[] array = new object[8];
                          array[0] = 0;
                          array[1] = intCaseNo;
                          array[2] = DateTime.Today;
                          array[3] = strUser;
                          array[4] = fees;
                          array[5] = 0;
                          array[6] = fees;
                          array[7] = true;
                          pTable.Rows.Add(array);
                      }
                  }
              }
              return pTable;
          }
  
          catch (Exception eX)
          {
              throw new Exception("cAllocation: Error in NewAllocations()" + Environment.NewLine + eX.Message);
          }
  </code></pre>
  
  <p>When I step through the code I can see that the error is thrown on the second occasion the following line is accessed:</p>
  
  <pre><code>pTable.Rows.Add(array);
  </code></pre>
  
  <p>Given that I create a new object array each time the code enters the loop, I fail to see why I am receiving this error message, which suggests to me the same row is being added multiple times.  Why does the code see each loop as adding the same datarow when the row is generated by a new object array each time?</p>