Duplicate keys

  • Thread starter Thread starter bbawa1
  • Start date Start date
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();
 
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
 
Back
Top