0

テキストボックスに何も入力しないか null 値を入力すると、エラーが発生します。私のコードは次のようなものです:

 SqlCommand cmd = con.CreateCommand();
 cmd.CommandText = "INSERT INTO Records 
                   ([Student ID], [First Name], [Last Name], [Middle Initial], 
                     Gender, Address, Status, Year, Email, Course, 
                    [Contact Number]) 
                    VALUES (@StudentID, @FirstName, @LastName , @MiddleInitial, 
                            @Gender, @Address, @Status, @Year, @Email, @Course, 
                            @ContactNumber)";

   SqlParameter p1 = new SqlParameter("@StudentID", SqlDbType.NChar);
   p1.Value = textBox1.Text;
   cmd.Parameters.Add(p1);
   SqlParameter p2 = new SqlParameter("@FirstName", SqlDbType.NVarChar);
   p2.Value = textBox2.Text;
   cmd.Parameters.Add(p2);
   SqlParameter p3 = new SqlParameter("@LastName", SqlDbType.NVarChar);
   p3.Value = textBox3.Text;
   cmd.Parameters.Add(p3);
   SqlParameter p4 = new SqlParameter("@MiddleInitial", SqlDbType.NChar);
   p4.Value = comboBox1.Text;
   cmd.Parameters.Add(p4);
   SqlParameter p5 = new SqlParameter("@Gender", SqlDbType.NChar);
   p5.Value = comboBox2.Text;
   cmd.Parameters.Add(p5);
   SqlParameter p6 = new SqlParameter("@Address", SqlDbType.VarChar);
   p6.Value = textBox4.Text;
   cmd.Parameters.Add(p6);
   SqlParameter p7 = new SqlParameter("@Status", SqlDbType.NChar);
   p7.Value = comboBox3.Text;
   cmd.Parameters.Add(p7);
   SqlParameter p8 = new SqlParameter("@Year", SqlDbType.VarChar);
   p8.Value = comboBox4.Text;
   cmd.Parameters.Add(p8);
   SqlParameter p9 = new SqlParameter("@Email", SqlDbType.VarChar);
   p9.Value = textBox5.Text;
   cmd.Parameters.Add(p9);
   SqlParameter p10 = new SqlParameter("@Course", SqlDbType.VarChar);
   p10.Value = comboBox5.Text;
   cmd.Parameters.Add(p10);
   SqlParameter p11 = new SqlParameter("@ContactNumber", SqlDbType.VarChar);
   p11.Value = textBox6.Text;
   cmd.Parameters.Add(p11);

   textBox1.Text = "";
   textBox2.Text = "";
   textBox3.Text = "";
   textBox4.Text = "";
   textBox5.Text = "";
   textBox6.Text = "";
   comboBox1.Text = "";
   comboBox2.Text = "";
   comboBox3.Text = "";
   comboBox4.Text = "";
   comboBox5.Text = "";
   if (cmd.Parameters.Contains(System.DBNull.Value))
   {
       MessageBox.Show("Please complete the fields", "Information...", 
                       MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                       MessageBoxDefaultButton.Button1);
    }
    else
    {
       MessageBox.Show("Data Inserted!", "Information ... ", 
                       MessageBoxButtons.OK, MessageBoxIcon.Information, 
                       MessageBoxDefaultButton.Button1);
    }
    cmd.ExecuteNonQuery();
    con.Close();

エラーは次のとおりです。

if(cmd.Parameters.Contains(System.DBNull.Value))

SQL Server と C# を使用しています。

4

4 に答える 4