Click here to Skip to main content
15,882,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

Please tell me how do i check duplicate entry in databse column before inserting the data.
i have column called company name(not a primary key)

thank you
Posted
Comments
[no name] 7-May-13 7:02am    
You write a query....
Johnny J. 7-May-13 9:14am    
Helpful. Why bother writing a comment at all?
[no name] 7-May-13 21:35pm    
Mostly because it directly answers the almost-but-not-quite question.
[no name] 7-May-13 7:03am    
what query..??

C#
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [company] Where companyname='" + Textbox.Text.Trim() + "'", connection);
              DataSet ds = new DataSet();
              da.Fill(ds);
              if (ds.Tables[0].Rows.Count == 0)
              {
                 MessageBox.Show("Company name Not found");
              }else
              {
                  MessageBox.Show("Company name Already exist");
               }
 
Share this answer
 
Comments
Johnny J. 7-May-13 9:13am    
A few comments:
1) You shouldn't instanciate an SqlDataAdapter and a DataSet just for this - it uses unnecessary memory
2) You shouldn't concatenate the query using "+" or "&" - it makes the code vulnerable to sql injections. You should use Sql Parameters
KM Perumal 8-May-13 0:43am    
I ve given for example only Johnny
VB
Public Function CompanyNameExists(ByVal companyName As String) As Boolean
    Dim query As String = "SELECT Count(*) FROM [yourtable] WHERE CompanyName=@CompanyName"
    Dim rowCount As Integer

    Using conn As New SqlConnection("your sql connection string")
        conn.Open()

        Using comm As New SqlCommand(query, conn)
            comm.Parameters.AddWithValue("@CompanyName", companyName)

            rowCount = Convert.ToInt32(comm.ExecuteScalar())
        End Using
    End Using

    Return (rowCount > 0)
End Function
 
Share this answer
 

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