从datagridview插入空值

时间:2014-11-04 12:02:49

标签: c# entity-framework datagridview

当我将单元格留空时,我试图从datagridview插入空值。这就是我正在做的事情:

using (var context = new EmployeeEntities())
{
  EMPLOYEE emp= new EMPLOYEE ();
  foreach (DataGridViewRow row in dgvLoadTable.Rows)
  {
   if (row.Cells[0].Value != null)
   {
     emp.EMP_ID = int.Parse(row.Cells[0].Value.ToString());
     emp.DEPARTMENT = row.Cells[2].Value is DBNull ? string.Empty : row.Cells[2].Value.ToString();
     //Also tried: emp.DEPARTMENT = row.Cells[2].Value is DBNull ? DBNull.Value.ToString() : row.Cells[2].Value.ToString();
     context.EMPLOYEE.AddObject(emp);
     context.SaveChanges();
                }
            }
 }

但它不起作用,当我尝试插入空值时,它会抛出“对象引用未设置为对象的实例”异常。我在这里做错了什么?

0 个答案:

没有答案