Domanda

I have a listBox with a DataTable datasource. I am trying to create a button that will move a DataRow up the DataTable.

This is the code that i am trying. But when it runs, it removes the correct Datarow, but inserts a blank row in the correct place.

DataRow row;            
row = SelectedPlayersHome.Rows[selectedIndex];
int temp = SelectedPlayersHome.Rows.IndexOf(row);
SelectedPlayersHome.Rows.RemoveAt(temp);
SelectedPlayersHome.Rows.InsertAt(row, temp - 1);

Even though i am creating a copy of the row, it appear that when i remove the row from the table, it deletes the data from the newly created row.

Ideas on how to fix this?

È stato utile?

Soluzione

By doing so:

row = SelectedPlayersHome.Rows[selectedIndex];

In fact you are not creating a copy of the row, but you assign a reference of the row to row variable.

You should do sth like this:

DataRow row = SelectedPlayersHome.NewRow();             
DataRow selectedRow= SelectedPlayersHome.Rows[selectedIndex];
row.ItemArray= selectedRow.ItemArray; // <-- copy data
SelectedPlayersHome.Rows.Remove(selectedRow);
SelectedPlayersHome.Rows.InsertAt(row, selectedIndex +1/-1); // depending if you want to go up or down
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top