Click here to Skip to main content
15,888,968 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am a learner.. i am creating a database where the fields are consumr_id,consumr_nm,consumr_add & consumr_cn

i want to check whether the consumr_cn(consumer contact no)is duplicate or not whenever i save the data.. if its a duplicate one, msgbox will show a message or error will be detected..... my code is:-

VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        
            cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DIGISMART\details.mdb")
            cn.Open()
            str = "Insert into consumer_details values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')"
            cmd = New OleDbCommand(str, cn)
            icount = cmd.ExecuteNonQuery
            MessageBox.Show(icount & " items added")
            CONN()
            FILL()
            cn.Close()
End Sub



what will be the code to check duplicate data or not and where it should be placed in my code??? pls help..
Posted

1 solution

Try by adding a unique constraint on the column consumr_cn.

http://msdn.microsoft.com/en-us/library/ms177420(v=sql.105).aspx[^]


Then try to catch this catch exception in your C# code behind.

C#
Try
Catch ex As SqlException
			
	If ex.Message.Contains("UniqueConstraint") Then
              ' do something
	End If
End Try


It is maybe not the most elegant solution but it works.


Cheers


EDIT:

SqlException has a collection of SqlError objects: Errors. The SqlError have properties for error Number and you can compare this with the known constraint violation error numbers (eg. 2627).

While is true that SqlException itself exposes a Number property, it is not accurate if multiple errors happen in a single batch and hence is better to inspect the Errors collection.
 
Share this answer
 
v3
Comments
Menon Santosh 7-Sep-12 7:57am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900