Dinav Ahire
Dinav Ahire

Reputation: 583

Procedure or function has too many arguments specified

There are so many questions on SO on this exception. But none of them are useful to me.

Here is my Stored Procedure :

CREATE PROCEDURE HolidayStandardMappingInsert 
    @HolidayID bigint,
    @StandatdID smallint
AS
BEGIN
    INSERT INTO HolidayStandardMapping VALUES(@HolidayID,@StandatdID)
END
GO

And here is my Code:

int StdId = 0;
                SqlCommand cmdS = new SqlCommand("HolidayStandardMappingInsert", conn);
                cmdS.CommandType = CommandType.StoredProcedure;


                for (int i = 0; i < cblStandard.Items.Count; i++)
                {
                    if (cblStandard.Items[i].Selected == true)
                    {
                        if (StdId == 0)
                            StdId = Convert.ToInt32(cblStandard.Items[i].Value);
                        else
                            StdId = Convert.ToInt32(cblStandard.Items[i].Value);
                        cmdS.Parameters.AddWithValue("@HolidayID", NewRecordID);
                        cmdS.Parameters.AddWithValue("@StandatdID", StdId);
                        if (conn.State == ConnectionState.Open)
                        {
                            conn.Close();
                        }
                        conn.Open();
                        int res = cmdS.ExecuteNonQuery();
                        if (res > 0)
                        {

                        }
                    }
                }

Tell me what is missing?

Upvotes: 0

Views: 2614

Answers (3)

Towhidul Islam Tuhin
Towhidul Islam Tuhin

Reputation: 1249

Each time You are adding cmdS.Parameters.AddWithValue in a loop. So after the first iteration, it has already 2 parameters.

You need to clear the command parameters by cmdS.Parameters.Clear() before entering the loop.

Upvotes: 0

Abdul Rehman Sayed
Abdul Rehman Sayed

Reputation: 6672

You are adding parameters in a loop. So after second iteration, your command has 4 parameters.

Upvotes: 2

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

You are using same SqlCommnad object for multiple insertions so previously added parameters are also present.

So either create a new SqlCommnad object inside loop or clear prevoius parameters.

This is how you can Clear Previously added parameters.

cmdS.Parameters.Clear();

Upvotes: 3

Related Questions