Search code examples
c#.netdatatableado.netdataadapter

Unable to get recently added records with getchanges method


This is my table:

Student:StudentId int PK autoincrement,Name varchar(20)

When I am adding new row to data table and updating it to send it to database then it works fine but I am trying to get recently added rows then I am getting null.

This is my code:

 using (var connection = new SqlConnection("MyConnectionstring"))
            {
                connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter();
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

                adapter.SelectCommand = new SqlCommand("select * from Student", connection);


                DataTable dt = new DataTable();
                adapter.Fill(dt);

                DataRow row = dt.NewRow();
                row["Name"] = "Abc";
                dt.Rows.Add(row);
                adapter.Update(dt);
                var addedRecords = dt.GetChanges(DataRowState.Added); //getting null here
                connection.Close();
            }  

However I have added student Abc but I am getting null in this line:

var addedRecords = dt.GetChanges(DataRowState.Added); //getting null here

Solution

  • See this MSDN page for DataAdapter.Update():

    1. DataRow.AcceptChanges is called. This will raise both the DataTable.RowChanging and DataTable.RowChanged events for the updated DataRow.

    AcceptChanges is being called for you by Update().

    If we look at the MSDN page for AcceptChanges():

    When invoking AcceptChanges, the EndEdit method is implicitly called to end any edits. If the RowState of the row was Added or Modified, the RowState becomes Unchanged. If the RowState was Deleted, the row is removed.

    That's why your GetChanges() call isn't returning anything -- there are no changes anymore.