繁体   English   中英

在现有数据表中插入一行

[英]Insert a Row in Existing 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;

    }

我收到此运行时错误:此行已经属于另一个表。 我尝试了不同的方法来插入,但错误是相同的,我也提到了一些帖子,但它似乎不起作用,请帮助!!

更改此:

var rowTemp = temp.NewRow(); 

对此:

var rowTemp = curvePoints.NewRow(); 

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

您的代码的这一部分:

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(); var rowTemp = curvePoints.NewRow();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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