How to insert row at any desired position in datatable?
I have a datatable which contains 10 rows. I now need to insert 11th row at the position specified by some conditions.
I have tried the InsertAt method but that gives the error of "this row already belongs to another table".
I cannot use ImportRow method as that simply import the rows into datatable and inserts the row at the end of the existing rows.
What should i do? Kindly help!
Thanks
UPDATED CODE
int iCount = 0;
foreach (DataRow dr in dtWithBundle.Rows)
{
DataRow drClone = dtOppClone.NewRow();
drClone.ItemArray = dr.ItemArray;
dtOpps.Rows.InsertAt(drClone, iIndex + iCount);
//dtOpps.ImportRow(drClone);
//dtOpps.Rows.Add(drClone.ItemArray); // Co开发者_运维问答mmented on Aug-4 2011 1700HRS
iCount++;
dtOpps.AcceptChanges();
}
Try this. I think the error you are getting is bcz you are not creating NewRow.
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
DataRow dr;
dr = dt.NewRow();
dr[0] = "A";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "C";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "B";
dt.Rows.InsertAt(dr,1);
foreach (DataRow d in dt.Rows)
{
Console.WriteLine(d[0].ToString());
}
Console.Read();
A DataTable is like an SQL table. It doesn't really have the concept of physical positions. You have to give the row a value that will sort the way you want it to when retrieving a set of rows.
[Edit] The documentation is a bit nebulous:
The location specified by InsertAt is reflected by the order of rows in the DataRowCollection only. If more than one row is returned in a DataRow array, the inserted row may not be returned in the location specified by InsertAt.
For more info, check
DataRowCollection.InsertAt Method
The example below shows you how to insert multiple rows at different positions, where the positioning may change, thus row number count in the DataTable.
Note the use of r and rNo:
'sum classifications in a budget
Dim ClassID As Integer = 0
Dim ClassTotal As Decimal = 0
Dim GrandTotal As Decimal = 0
Dim rNo As Integer = 0
Dim rw As DataRow = Nothing
Dim RowCount As Integer = dt.Rows.Count
For r As Integer = 0 To RowCount - 1
If ClassID <> dt.Rows(rNo)("ClassificationID") Then
If rNo <> 0 Then
'add sub total
rw = dt.NewRow()
rw("Classification") = "Sub-Total"
rw("Amount") = ClassTotal
dt.Rows.InsertAt(rw, rNo)
'reset sub total
ClassTotal = 0
'increment row count because of inserted row
rNo += 1
End If
ClassID = dt.Rows(rNo)("ClassificationID")
End If
ClassTotal += dt.Rows(rNo)("Amount")
GrandTotal += dt.Rows(rNo)("Amount")
rNo += 1
Next
'add grand total
rw = dt.NewRow
rw("Classification") = "Sub-Total"
rw("Amount") = ClassTotal
dt.Rows.Add(rw)
'add grand total
rw = dt.NewRow
rw("Classification") = "Grand Total"
rw("Amount") = GrandTotal
dt.Rows.Add(rw)
*Code in VB.net. Please convert to C# for your use
精彩评论