ASP.net使用gridview删除行

时间:2014-08-27 13:02:13

标签: c# asp.net gridview wizard delete-row

我正在尝试使用为gridview向导提供的删除功能删除一行。

但是当我点击删除时,我得到以下错误:

An exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll but was not handled in user code

这是我的代码:

 public void deleteProject(DAL.Project p)
    {
        DAL.Project result = (from project in dc.Projects
                              where project.pk_project_id == p.pk_project_id
                              select project).Single();
        dc.Projects.DeleteOnSubmit(result);
        dc.SubmitChanges();
    }

当我调试它时,值“p”没有属性。

奇怪的是,当我想更新我的行时,我使用的方法有点相同:

 DAL.Project result = (from project in dc.Projects
                              where project.pk_project_id == p.pk_project_id
                              select project).Single();
        result.titel = p.titel;
        result.beschrijving = p.beschrijving;

        dc.SubmitChanges();

这很顺利。那么为什么它不能用于删除行?

1 个答案:

答案 0 :(得分:1)

如果序列包含多个项目或输入序列为空,则

Enumerable.Single会抛出InvalidOperationException。您可以使用FirstFirstOrDefault

DAL.Project result = (from project in dc.Projects
                      where project.pk_project_id == p.pk_project_id
                      select project).FirstOrDefault();
if(result != null)
{
     // ...
}

(但是,我不知道更新的原因)