user997413
user997413

Reputation:

No Duplicate Primary Key

I am working on a school activity. This is my sample form:

sample form http://i53.tinypic.com/14xlrl.png

What I'm trying to do is that when a user adds a record that has the same CourseID (Primary Key) with one of the records listed, there should be some Message box that will appear that says "Cannot insert same CourseID or cannot duplicate CourseID (Because PRIMARY KEY cannot be DUPLICATED)."

Upvotes: 0

Views: 1713

Answers (3)

onedaywhen
onedaywhen

Reputation: 57023

Your Course_ID column looks to be redundant. Suggestion: drop Course_ID and declare a unique constraint on Course_Code using a meaningful name. When an update would cause a duplicate Course_ID value, the DBMS will automatically reject the update and generate an erro. You should ensure this error is exposed to your application, including the meaningful name, for your application to handle gracefully.

Upvotes: 1

Haedrian
Haedrian

Reputation: 4328

As said by others, don't let the user enter the primary key. However if you really must.

Select Count(*) from tablename where CourseID = [whatever]

If Count returns 1, then it means there's already a record with that id, and throw an error.

An alternative is to just try the Insert function which should throw an exception, then handle that.

Upvotes: 0

RKh
RKh

Reputation: 14161

I believe you are manually inserting CourseID. A better way is to make the CourseID column auto-incrementing in SQL Server.

Secondly, if you seriously created a primary key, it won't accept duplicates. You only need to catch the Exception. Check these links on Exception Handling:

Throwing Exceptions in C#

Exceptions and Exception Handling (C# Programming Guide)

Upvotes: 4

Related Questions