C# - 删除选定的DataGridView行

时间:2015-04-20 10:12:30

标签: c# sql-server datagridview

我有以下代码,当我从DataGridView中选择一行时,我想从MSSQL数据库中删除。关键是,代码正在工作(部分),但是在我关闭表单并重新打开它之后,记录仍然存在且DB尚未更新。会出现什么问题?感谢。

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);}

2 个答案:

答案 0 :(得分:0)

正如您已经说过,您的代码部分正常工作,并且germi也是正确的说明,您不会将更改写入数据库。

执行此操作的一种方法是执行以下操作:

收集集合中所有选定的行ID。 在删除语句中使用该集合到您的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());
}

这将删除服务器上的所有选定行。如果您没有上下文,则可能需要应用其他技术。

可以在此处找到使用AdventureWorks数据库的小型演示:http://share.linqpad.net/767on5.linq

答案 1 :(得分:-1)

相关问题