【问题标题】:C# - delete a selected DataGridView rowC# - 删除选定的 DataGridView 行
【发布时间】:2015-04-20 10:12:30
【问题描述】:

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

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

【问题讨论】:

  • 您只是从 DataGridView 中删除行 - 您的代码中没有任何内容与数据库通信。

标签: c# sql-server datagridview


【解决方案1】:

正如您已经说过的那样,您的代码正在部分工作,germi 也正确地指出,您不会将更改写入数据库。

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

收集集合中所有选定的行 ID。 在您的 sql 服务器的删除语句中使用该集合。

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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 2011-06-05
    • 2015-05-04
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多