简体   繁体   中英

Delete selected rows from DataGridView and Database

I want to delete the selected rows from DataGridView and this delete should affect the database. I'm using the Entity Framework and that is my code which did not work.

private void button4_Click(object sender, EventArgs e)
{
    var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
    var TE = new TaskEntities();
    var UD = new userdata();
    UD = TE.userdatas.First(c => c.ID == toBeDeleted);
    TE.DeleteObject(UD);
    TE.SaveChanges();
}

Is your DGV bound to any dataSource? Is so, delete row from datasource, and then do use Update command (or update sql query) to do chnages in database.

try this:

private void button4_Click(object sender, EventArgs e)
{
     var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
     var TE = new TaskEntities();
     var userdata = TE.userdatas.First(c => c.ID == toBeDeleted);
     TE.userdatas.Remove(userdata);
     TE.SaveChanges();
     dataGridView1.DataSource = TE.userdatas;
}

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