DataTable, Delete, GetChanges, Merge....What's wrong?

G

Guest

/*
The following code :
Creates a DataTable with four fields.
Copies the table in a DataSet.
Message Box displays 0 rows.
Adds three rows to the DataTable
Merges the DataTable into the DataSet
Message Box displays 3 rows.
Deletes one row from the DataTable
Merges the DataTable.GetChanges() into the DataSet
Message Box displays 4 rows!!!!

Why in the world does the DataSet have 4 rows??? I loop through the Rows
and check RowState and none of them are marked deleted?? This is confusing,
am I doing something wrong??

*/

private void button2_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet("TestDataSet");
DataTable dt = new DataTable("Test1");

DataColumn NewCol = dt.Columns.Add("dt2Test11",
System.Type.GetType("System.String"));
NewCol.Caption = "dtTest1";

NewCol = dt.Columns.Add("dt2Test12",
System.Type.GetType("System.String"));
NewCol.Caption = "dtTest12";

NewCol = dt.Columns.Add("dt2Test13",
System.Type.GetType("System.String"));
NewCol.Caption = "dtTest13";

NewCol = dt.Columns.Add("dt2Test14",
System.Type.GetType("System.String"));
NewCol.Caption = "dtTest14";

ds.Tables.Add(dt.Copy());
MessageBox.Show("Test1 rowCount: " +
Convert.ToString(ds.Tables["Test1"].Rows.Count));

for (int x = 0; x < 3; x++)
{
DataRow newRow = dt.NewRow();
newRow["dt2Test11"] = "Test" + Convert.ToString(x);
newRow["dt2Test12"] = "Cost" + Convert.ToString(x);
newRow["dt2Test13"] = Convert.ToString(x);
newRow["dt2Test14"] = "Status" + Convert.ToString(x);
dt.Rows.Add(newRow);
}

ds.Tables["Test1"].Merge(dt);

MessageBox.Show("Test1 rowCount: " +
Convert.ToString(ds.Tables["Test1"].Rows.Count));
dt.AcceptChanges();
dt.Rows[0].Delete();
ds.Tables["Test1"].Merge(dt.GetChanges(), false,
MissingSchemaAction.Error);

MessageBox.Show("Test1 rowCount: " +
Convert.ToString(ds.Tables["Test1"].Rows.Count));

}
 
M

Marina Levit [MVP]

Deleting a row means the row is marked for deletion. So that the next time
you call Update on your data adapter, it knows to go deleted that row.
It does not mean the row is physically removed. If it was physically
removed, then the adapter would not know to go delete it from the database
during the update.

If you want to physically remove the row, then use the Remove method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top