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.
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()
Comment