By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,115 Members | 894 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,115 IT Pros & Developers. It's quick & easy.

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

P: 7
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.

Expand|Select|Wrap|Line Numbers
  1. Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  2.         Try
  3.             myConnection = New SqlConnection("server=local\SQLEXPRESS;uid=sa;password=12345;database=My DB")
  4.             myConnection.Open()
  5.  
  6.             If TextBox1.Text = "" Then
  7.                 MsgBox("Please Insert a valid Commodity Name")
  8.             Else
  9.                 scalarCommand = New SqlCommand("Select count(*) as [Recordcount] from Commodity where Commodity_Name = " & TextBox1.Text & "", myConnection)
  10.                 recordcount = scalarCommand.ExecuteScalar()
  11.                 If Recordcount = 0 Then
  12.                     myCommand = New SqlCommand("Insert into Commodity   ([Commodity_Name], [Section_ID]) values ('" & TextBox1.Text & "','" & ComboBox1.SelectedValue & "')", myConnection)
  13.                     myCommand.ExecuteNonQuery()
  14.                     myConnection.Close()
  15.                     MessageBox.Show("New Record Added")
  16.                 Else
  17.                     MsgBox("An entry with the same name already exists")
  18.                 End If
  19.             End If
  20.  
  21.         Catch ex As Exception
  22.             Console.WriteLine("Error : " & ex.ToString)
  23.  
  24.         Finally
  25.             myConnection.Close()
Dec 22 '09 #1
Share this Question
Share on Google+
1 Reply


tlhintoq
Expert 2.5K+
P: 3,525
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.
Dec 22 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.