Duplicate keys

B

bbawa1

Hi,

I have dropdownlist named ddlapplication in my web form. When I
click any item it insert
that record in database with primary key and show in gridview.
If user try to add the same record next time by clicking same item
from the dropdown list
which already exist in database it should show error message that
this
record alredy exist or in other words before inserting it should check
wheather the record is already in database or not.

How can I do that. Here is my code

string str1 = this.ddlApplication.DataTextField;
string str2 = this.ddlApplication.SelectedValue;
string str3 = this.ddlPermission.SelectedItem.Value;


String constr =
System.Configuration.ConfigurationManager.ConnectionStrings["twcsanConnectionString"].ConnectionString;
SqlConnection objConn = new SqlConnection(constr);
SqlCommand objCmd = new SqlCommand("INSERT INTO
tbUsersAppRights(AppId, AppRightId, UserId) " +
"VALUES (@str1,@str2,@str3)", objConn);
objCmd.Parameters.AddWithValue("@str1",
int.Parse(this.ddlApplication.SelectedValue));
objCmd.Parameters.AddWithValue("@str2",
int.Parse(this.ddlPermission.SelectedValue));
objCmd.Parameters.AddWithValue("@str3",
int.Parse(this.lblUserid11.Text));

objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
this.gdAddUser.DataBind();
 
G

Guest

Hi,

I have dropdownlist named ddlapplication in my web form. When I
click any item it insert
that record in database with primary key and show in gridview.
If user try to add the same record next time by clicking same item
from the dropdown list
which already exist in database it should show error message that
this
record alredy exist or in other words before inserting it should check
wheather the record is already in database or not.

How can I do that. Here is my code

1. Make a select before

SELECT count(*) FROM tbUsersAppRights WHERE ...

if it returned 0 -> no records found and you can INSERT INTO

otherwise, show an error message

2. Exception handling using try...catch

3. Use a stored procedure
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top