Help needed with checking for a duplicate on Table before inserting the field

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Orbie
    New Member
    • Nov 2009
    • 7

    Help needed with checking for a duplicate on Table before inserting the field

    Hi All,
    I'm new to VB.NET and i'm looking for some help with my Windows Form. I need to check if a Commodity entered into (TextBox1.Text) already exists on my table before i insert it. I'm having issues checking if the number of rows returned from my Select is equal 0? Also i'm wondering should i be checking for an exception and open/closing my connections each time i make a call to my DB or is the way i have it coded below OK??

    Any input would be appreciated, thanks.

    Code:
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            Try
                myConnection = New SqlConnection("server=local\SQLEXPRESS;uid=sa;password=12345;database=My DB")
                myConnection.Open()
    
                If TextBox1.Text = "" Then
                    MsgBox("Please Insert a valid Commodity Name")
                Else
                    scalarCommand = New SqlCommand("Select count(*) as [Recordcount] from Commodity where Commodity_Name = " & TextBox1.Text & "", myConnection)
                    recordcount = scalarCommand.ExecuteScalar()
                    If Recordcount = 0 Then
                        myCommand = New SqlCommand("Insert into Commodity   ([Commodity_Name], [Section_ID]) values ('" & TextBox1.Text & "','" & ComboBox1.SelectedValue & "')", myConnection)
                        myCommand.ExecuteNonQuery()
                        myConnection.Close()
                        MessageBox.Show("New Record Added")
                    Else
                        MsgBox("An entry with the same name already exists")
                    End If
                End If
    
            Catch ex As Exception
                Console.WriteLine("Error : " & ex.ToString)
    
            Finally
                myConnection.Close()
    Last edited by tlhintoq; Dec 22 '09, 03:14 PM. Reason: [CODE] ...Your code goes between code tags [/CODE]
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

    Comment

    Working...