0

I am using Visual Studio to create an asp.net web application in C# and am having issues trying to insert data from one of my pages into a table in a SQL Server database. I am getting the following error message:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: The variable name '@' has already been declared. Variable names must be unique within a query batch or stored procedure.

My code looks like this;

Block of code

I have tried a few different things but I keep getting the same error and I've been on here and youtube for nearly an hour now and I can't find anything that relates to my issue. Any help would be greatly appreciated.

Thanks!

Edit: I should add that I got this code from youtube and in the video, it worked fine. The only real difference is that my version is within an 'if' statement. I commented the if statement out and received the same error message.

1 Answer 1

1

You code is wrong. First, your sql query is incomplete; you need to include the actual variable names as part of your INSERT script:

INSERT INTO parent(parentID) VALUES (@parentID)

Then in your C# code, you need to include the exact name of the parameter when adding it to the collection:

xp.Parameters.AddWithValue("@parentID", userBox.Text);

This is obviously for one parameter, you'll need to repeat the same pattern for the rest. Read more here.

Sign up to request clarification or add additional context in comments.

3 Comments

One more question, for one of the entries in another part of the app, I need to be able to include DOB, which I have as 3 drop downs. How do I take the 3 different values and insert them into 1 (@dob) table field in my database? Cheers.
That's a different question, but if you column type is datetime, create a DateTime object from the values in C# and insert them to the database.
You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.