NULL值问题 - 数据库表

时间:2013-06-29 08:25:04

标签: c# .net sql-server

我创建了一个名为“Assignment”的表,其中包含两列assignment_id(主键)和assignment_title,两者都设置为不允许输入空值。这里我的代码显示了插入和修改功能。修改工作正常但是因为我在其中插入任何值总是生成异常“无法将值NULL插入列'assignment_title',表'news.dbo.Assignment';列不允许空值.INSERT失败。”我附上了图片,让你清楚。 enter image description here enter image description here 请指导我解决这个问题。谢谢!

 private void dgData_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            if (e.EditAction == DataGridEditAction.Commit)
            {
                //Database context
                DataClasses1DataContext objNewContext = new DataClasses1DataContext();

                //Creates new object to insert new Record in Database
               Assignment objStudentDetail = new  Assignment ();

                //Check if record is not is table then preoceed to insert
                if (!objContext. Assignments.Contains(student))
                {
                    objStudentDetail.assignment_title = string.IsNullOrEmpty(student.assignment_title) ? student.assignment_title : student.assignment_title.Trim();

                    //This will insert new record in table
                    objNewContext. Assignments.InsertOnSubmit(objStudentDetail);

                    //This will update changes in database
                    objNewContext.SubmitChanges();

                    //Show message when record is inserted
                    txtStatus.Text = "Success: Data Inserted";
                }
                else
                {
                    //this will update changes in database for edit operation in database
                    objContext.SubmitChanges();
                    //Show message when record is updated
                    txtStatus.Text = "Success: Data Updated";
                }
            }
        }

1 个答案:

答案 0 :(得分:4)

异常表示assignment_title列中不允许使用NULL值。您确定objStudentDetail对象的标题中没有NULL吗?

修改下面的语句,就像当前形式一样,它不会保护您不具有NULL值:

objStudentDetail.assignment_title = string.IsNullOrEmpty(student.assignment_title) 
                                    ? student.assignment_title 
                                    : student.assignment_title.Trim();

到这一个:

objStudentDetail.assignment_title = student.assignment_title == null
                                    ? string.Empty 
                                    : student.assignment_title.Trim();