Search code examples
c#.netdatatabledatarowdatarowcollection

How do I populate a DataRow and assign it to one of two tables based on a condition?


I have data being processed by an app which needs to sort the data based on whether or not a bit is flipped. The tables are identical. The code as it stands looks something like this:

DataTable dt2 = dt1.Clone();

DataRow r = dt1.NewRow();
FillUp(ref r);

if(bitISetEarlier)
   dt2.ImportRow(r);
else
   dt1.ImportRow(r);

Now, a clear problem I was having is that if the row wasn't already attached to a table, ImportRow() fails silently and I end up with an empty table. When I changed this to:

    if(bitISetEarlier)
       dt2.Rows.Add(r);
    else
       dt1.Rows.Add(r);

I started getting an exception saying that a function was trying to add a row that existed for another table. So when I tried this:

if(bitISetEarlier)
    if(r.RowState == DataRowState.Detached) 
         dt2.Rows.Add(r) 
    else dt2.ImportRow(r);
 else
     if(r.RowState == DataRowState.Detached) 
          dt1.Rows.Add(r) 
     else dt1.ImportRow(r);

the exception stopped, but any attempt to assign to dt2 still states that the row belongs to another table, but if I comment out the dt2 if statement and just attempt ImportRow(), the dt2.Rows.Count remains at 0 and no records assigned.

I need to populate the DataRow before knowing which table it belongs in, but I have no idea what columns the row will have before it hits this function. The condition that indicates which table it should go to is not stored with the data in the DataTable.

Is the problem that even though they have identical columns, NewRow() is adding an attribute to the row that makes it incompatible with the sister table? Is there a way I can get the same functionality as NewRow() (copy schema without knowing what any of the columns are ahead of time) but that I can dynamically assign? I'm aware I could probably manually construct a row that is compatible with either by wrapping it in a for loop and building out the columns every time i need the new row using the DataTable.Columns property, but I'd like to avoid doing that if possible.


Solution

  • I found my solution. Since I can't add the row built off of one table to the other table directly, I figured it was the DataRow object that was problematic, but the ItemArray property was probably all I needed.

                        if (isErrorRow)
                        {                           
                            //nr is the NewRow for dt1
                            var nr2 = dt2.NewRow();
                            nr2.ItemArray = nr.ItemArray;
                            dt2.Rows.Add(nr2);
                        }
    

    This effectively cloned the rows.