简体   繁体   中英

Deleted Row in Datatable is not updated to SQL Server

I'm kinda new to C#, I usually code with VB.net and SQL command I have a small problem in my datatable: when I add a new row and or edit a row and save the changes, it all works fine, but when I delete a row, it does not get recorded on the server and the row say there my code for saving the changes as follow:

using (SqlConnection con = new SqlConnection(ConString))
{
    CmdString = "SELECT * FROM IncomingPapers";

    SqlCommand cmd = new SqlCommand(CmdString, con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);

    SqlCommandBuilder builder = new SqlCommandBuilder(sda);
    sda.UpdateCommand = builder.GetUpdateCommand();
    sda.DeleteCommand = builder.GetDeleteCommand();
    sda.InsertCommand = builder.GetInsertCommand();

    sda.Update(dt);
}

and the code for deleting a row from the datatable is:

dt.Rows.RemoveAt(PapersLV.SelectedIndex);
dt.AcceptChanges();

The row gets deleted from the datatable but when saving the changes are not saved to the server and all deleted rows return to normal

DataTable.AcceptChanges doesn't update the database table. It changes the DataRowState for every row in the DataTable to Unchanged and discards from memory every change you have made to the DataTable

If you want to use the SqlDataAdapter to Update the rows you should not use RemoveAt and AcceptChanges but you call the Delete on the Row and the Adapter Update method

dt.Rows[PapersLV.SelectedIndex].Delete();
sda.Update(dt);

This, of course, means that you need to have a reference to the SqlDataAdapter available at the point of the Delete action

Your current code use RemoveAt, but this removes the row from the DataTable (an in memory object) and doesn't leave any info for the Adapter to find the record on the database. Instead the Delete method doesn't remove the row, but changes the DataRowState to Deleted. Now the Adapter uses the primary key value from the deleted row to find the record to delete in the database.

You have to call da.Update(dt); before dt.AcceptChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM