Domanda

I have one sample code shown below.

DataRow dr = DTSource.Rows[rowIndex]; //getting specified index row
DTSource.Rows.RemoveAt(rowIndex); // deleting specified row
DTSource.Rows.InsertAt(dr, rowIndex - 1); // adding the row placed just above of the deleted row

Here, after inserting the particular row to the specified index, the data table showing an empty row at the recently inserted place. How can i add the row with the data instead of this empty row?

È stato utile?

Soluzione

Based on Mnieto and Tim Schmelter Answers, I have changed my code like this.

 DataRow dr = DTSource.NewRow();
                for (int i = 0; i < DTSource.Columns.Count; i++)                    
                    dr[i] = DTSource.Rows[rowIndex][i];

Now it's working for me.

Altri suggerimenti

dr is deleted. That is because data table shows an empty row. Let see step by step:

DataRow dr = DTSource.Rows[rowIndex];

You save a row in dr variable

DTSource.Rows.RemoveAt(rowIndex);

You delete that row. dr variable is now pointing to a deleted row.

DTSource.Rows.InsertAt(dr, rowIndex - 1);

You are inserting a deleted row in another position

If you want to move a row position you should to do a deep copy of the datarow.

Have a look at the documentation of RemoveAt:

Removes the row at the specified index from the collection. When a row is removed, all data in that row is lost. ...

So you need to persist the data temporarily, for example by using row.ItemArray

DataRow row = DTSource.Rows[rowIndex];         //getting specified index row
var data = row.ItemArray;                      // all fields of that row
DTSource.Rows.RemoveAt(rowIndex);              // removes row and it's data 
row.ItemArray = data;                          // reassign data
DTSource.Rows.InsertAt(row, rowIndex - 1);     // adding the row placed just above of
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top