Anon Anon - 1 month ago 6x
SQL Question

SqlException error when I insert into database

This is basically a method to insert a record into a table. It was working fine before I decided to add in a way to check if the Customer ID already exists in the database. I get a

'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Procedure or function InsertCustomer has too many arguments specified.

on the line


I don't understand what's wrong.

public void add()
lblMessage.Text = "";
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CheckDetails";
command.Parameters.AddWithValue("@CustID", txtCID.Text);
int check = (int)command.ExecuteScalar();

if (check == 0)
command.CommandText = "InsertCustomer";
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;
command.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFName.Text;
command.Parameters.Add("@Surname", SqlDbType.VarChar).Value = txtLName.Text;
command.Parameters.Add("@Gender", SqlDbType.VarChar).Value = rdoGender.Text;
command.Parameters.Add("@Age", SqlDbType.Int).Value = txtAge.Text;
command.Parameters.Add("@Address1", SqlDbType.VarChar).Value = txtAdd1.Text;
command.Parameters.Add("@Address2", SqlDbType.VarChar).Value = txtAdd2.Text;
command.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text;
command.Parameters.Add("@Phone", SqlDbType.VarChar).Value = txtPhone.Text;
command.Parameters.Add("@Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
command.Parameters.Add("@Email", SqlDbType.VarChar).Value = txtEmail.Text;


lblMessage.Text = "Customer Details Added.";
lblMessage.Text = "Customer ID already exists.";



You are adding the same parameter twice:

command.Parameters.AddWithValue("@CustID", txtCID.Text);
// ....
command.Parameters.Add("@CustID", SqlDbType.Int).Value = txtCID.Text;

You can use command.Parameters.Clear();. But i'd prefer to use two different SqlCommands for the two procedures CheckDetails and InsertCustomer to avoid such issues.

Side-note: don't let the database try-cast the value for you. Use int.TryParse.