简体   繁体   中英

Insert a Row in Existing DataTable

I tried a method for the question Asked.

public DataTable allSupportPoints(DataTable createPath, double rMax, double interval, int curveType)
    {
        List <DataTable> theCornerCurves = cornerCurves(createPath, rMax, interval, curveType);
        DataTable curvePoints = CustomMerge(theCornerCurves);

        double X1 = Convert.ToDouble(createPath.Rows[0][1]);
        double Y1 = Convert.ToDouble(createPath.Rows[0][2]);
        double X2, Y2;
        int count = curvePoints.Rows.Count;
        double theDistance;
        int pointInsert;
        for (int i = 0; i < count;)
        {
            X2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
            Y2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
            theDistance = distance(X1,Y1,X2,Y2);
            int j=0;
            if ( theDistance> interval)
            {
                pointInsert = Convert.ToInt32 (theDistance / interval);
                DataTable temp = straightLineGenerator(X1, Y1, X2, Y2,interval);
                for (j = 0; j < temp.Rows.Count; j++)
                {
                    var rowTemp = temp.NewRow(); 
                    rowTemp.ItemArray =    temp.Rows[j].ItemArray.Clone() as object[];
                    curvePoints.Rows.InsertAt(rowTemp, i + j);
                }
            }
            X1=Convert.ToDouble(curvePoints.Rows[i+j][0]);
            Y1 = 0;
            count = curvePoints.Rows.Count;
            i = i + 1;
        }
        return curvePoints;

    }

I get This runTime Error: This row already belongs to another table. I have tried different methods to Insert yet the error is same, i referred some posts also but it doesnt seem to work Please help!!!!

Change this:

var rowTemp = temp.NewRow(); 

to this:

var rowTemp = curvePoints.NewRow(); 

In fact the row must be created by the same table you want to add it

This part of your code:

for (j = 0; j < temp.Rows.Count; j++)
{
    var rowTemp = temp.NewRow(); 
    rowTemp.ItemArray = temp.Rows[j].ItemArray.Clone() as object[];
    curvePoints.Rows.InsertAt(rowTemp, i + j);
}

is incorrect. First you're adding new row to temp , and then trying to insert it into curvePoints . Since it already belongs to temp datatable - you're getting exception you've mentioned.

This code can be simplified as

for (j = 0; j < temp.Rows.Count; j++)
    curvePoints.ImportRow(temp.Rows[j]);

But note: ImportRow inserts row at last position, so if you really need to insert row into specific position like you're doing - just leave your code as is and only change var rowTemp = temp.NewRow(); to var rowTemp = curvePoints.NewRow();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM