在现有DataTable中插入一行

时间:2015-04-16 07:59:33

标签: c# datatable

我尝试了一个问题的方法。

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;

    }

我得到此runTime错误:此行已属于另一个表。 我尝试了不同的方法插入错误是相同的,我也提到了一些帖子,但它似乎没有工作 请帮忙!!!!

2 个答案:

答案 0 :(得分:2)

改变这个:

var rowTemp = temp.NewRow(); 

到此:

var rowTemp = curvePoints.NewRow(); 

实际上,该行必须由要添加的同一个表创建

答案 1 :(得分:0)

这部分代码:

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

不正确。首先,您要向temp添加新行,然后尝试将其插入curvePoints。因为它已经属于temp数据表 - 你得到了你提到的异常。

此代码可简化为

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

但请注意:ImportRow会在最后一个位置插入行,因此如果您确实需要像往常一样将行插入特定位置 - 只需按原样保留代码,只需将var rowTemp = temp.NewRow();更改为{ {1}}