0

Are there any gurus out there that might be able to help me figure this out? I keep throwing this exception in C#, but everything that I can see seems to be correct. Here is the code

  public bool Insert(loginBLL u)
    {
        bool isSuccess = false;
        SqlConnection conn = new SqlConnection(myconnstrng);

        try
        {
            String sql = "INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username) VALUES (@firstname, @lastname, @phone, @email, @address, @city, @state, @zipcode, @password, @username)";
            SqlCommand cmd = new SqlCommand(sql, conn);

            cmd.Parameters.AddWithValue("@firstname", u.firstname);
            cmd.Parameters.AddWithValue("@lastname", u.lastname);
            cmd.Parameters.AddWithValue("@phone", u.phone);
            cmd.Parameters.AddWithValue("@email", u.email);
            cmd.Parameters.AddWithValue("@address", u.address);
            cmd.Parameters.AddWithValue("@city", u.city);
            cmd.Parameters.AddWithValue("@state", u.state);
            cmd.Parameters.AddWithValue("@zipcode", u.zipcode);
            cmd.Parameters.AddWithValue("@password", u.password);
            cmd.Parameters.AddWithValue("@username", u.username);

         
            conn.Open();

            int rows = cmd.ExecuteNonQuery();
Joe W.
  • 1
  • 1

1 Answers1

0

I suspect your problem is due to passing (object)null instead of DBNull.Value for null parameters.

These days, I'd avoid all that parameter boilerplate by writing an extension method to bind parameters from a FormattableString.

        public static SqlCommand GetCommandInterpolated(this SqlConnection conn, FormattableString sql)
        {
            var cmd = conn.CreateCommand();
            var replacements = new string[sql.ArgumentCount];
            var args = sql.GetArguments();

            for (int i = 0; i < sql.ArgumentCount; i++)
            {
                var p = cmd.CreateParameter();
                cmd.Parameters.Add(p);
                p.ParameterName = replacements[i] = $"@p_{i}";
                p.Value = args[i] ?? DBNull.Value;
            }
            cmd.CommandText = string.Format(sql.Format, replacements);
            return cmd;
        }


        var cmd = conn.GetCommandInterpolated(
            $@"INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username)
            VALUES ({u.firstname}, {u.lastname}, {u.phone}, {u.email}, {u.address}, {u.city}, {u.state}, {u.zipcode}, {u.password}, {u.username}"
        );
Jeremy Lakeman
  • 9,515
  • 25
  • 29
  • Thank you all. Problem solved only to create a new one. Appreciate all of the input and help – Joe W. Jul 20 '20 at 02:04