Weird thing happening while using DataTable.Select()
DataTable dt = new DataTable();
DataRow[] dr;
dt.Columns.Add();
dt.Columns.Add();
dt.Rows.Add(1, 1);
dt.Rows.Add(2, 2);
dt.Rows.Add(3, 3);
dr = dt.Select();
dr[1].Delete();
foreach (DataRow x in dt.Rows)
MessageBox.Show(x[0] + " " + x[1]);
The MessageBox shows me "1 1" and "3 3". Why is this happening? I didn't manipulate the DataTable, just the DataRow[] that holds the values of the Da开发者_如何学运维taTable. So why did the values in the DataTable changed also? Can someone please explain this?
You are getting a reference to the selected rows in dr, they are not a copy. If you delete one then it is gone from dt.rows and dr.
Take a look at http://msdn.microsoft.com/en-us/library/system.data.datatable.acceptchanges.aspx
You need to call AcceptChanges after the delete:
dt.AcceptChanges();
dr
actually references the rows within the DataTable dt
. That's why it was deleted.
精彩评论