简体   繁体   中英

C# - delete a selected DataGridView row

I have the following code and I would like to delete from a MSSQL database when I select a row from a DataGridView. The point is, the code is working (partially), but after I close the form and I reopen it, the records are still there and DB have not been updated. What would be the problem? Thanks.

try
{
    if (MessageBox.Show("Doriti sa stergeti autogara?", "Stergere", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        foreach (DataGridViewRow item in this.grdAutogari.SelectedRows)
        {
            grdAutogari.Rows.RemoveAt(item.Index);
        }
    }
}
catch (Exception er) { MessageBox.Show(er.Message);}

As you already stated your code is working partially and germi is also right stating, that you don't write your changes to the database.

One way to do this, is do the following:

Collect all selected rows ids in a collection. Use that collection in a delete statement to your sql server.

if (MessageBox.Show("Doriti sa stergeti autogara?", "Stergere", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
    //parameters cant be System.Int32[]
    var IdsToDelete = new List<string>();
    foreach (DataGridViewRow item in this.grdAutogari.SelectedRows)
    {
        grdAutogari.Rows.RemoveAt(item.Index);
        //you probably need to use item.ID or the column that holds your 
        //Primary key for your sql statement
        IdsToDelete.Add(item.Index.ToString());
    }
    //assuming you have a DataContext of some sort. 
    //Maybe Entity Framework or Linq-To-Sql
    db.ExecuteCommand("delete from [YOURTABLENAME] where YOURTABLENAME.Id in ({0})", IdsToDelete.ToArray());
}

This will delete all selected rows on your server. If you dont have a context, you might need to apply a different technique.

A small demo using the AdventureWorks database can be found here: http://share.linqpad.net/767on5.linq

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