foreach (DataGridViewRow row in dg1.Rows)
{
string constring = @"Data Source=localhost;Initial Catalog=RecruitmentDB;User ID=sa";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO ApplicantFamilyBackground(lastName,firstName,middleName,relationship,applicantcode) VALUES(@lastName, @firstName, @middleName, @relationship, @applicantcode)", con))
{
cmd.Parameters.AddWithValue("@lastName", row.Cells["dglastname"].Value);
cmd.Parameters.AddWithValue("@firstName", row.Cells["dgfirstname"].Value);
cmd.Parameters.AddWithValue("@middleName", row.Cells["dgmiddlename"].Value);
cmd.Parameters.AddWithValue("@relationship", row.Cells["dgrelationship"].Value);
cmd.Parameters.AddWithValue("@applicantcode",row.Cells["dgapplicantcode"].Value = lblapplicantcode.Text.ToString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
答案 0 :(得分:1)
发生异常是因为从@lastName
拉出的row.Cells["dglastname"].Value
的值为null
,因此SqlParameter
的值必须设置为DBNull.Value
}。
修复它的一种方法是更换参数初始化,如下所示:
cmd.Parameters.AddWithValue("@lastName", row.Cells["dglastname"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@firstName", row.Cells["dgfirstname"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@middleName", row.Cells["dgmiddlename"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@relationship", row.Cells["dgrelationship"].Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("@applicantcode", row.Cells["dgapplicantcode"].Value = lblapplicantcode.Text != null ? lblapplicantcode.Text.ToString() : DBNull.Value);