Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 25th, 2012  |  syntax: None  |  size: 2.16 KB  |  hits: 27  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Looking for the best way to use ExecuteScalar()
  2. Dim objParentNameFound As Object
  3.  
  4. TextBoxParentsName.Text = ""
  5.  
  6. If TextBoxParentID.Text <> "" Then
  7.  
  8.     ' Display the parent's name using the parent ID. '
  9.     Dim strSqlStatement As String = "Select FatherName " & _
  10.                                       "From Parents " & _
  11.                                      "Where ID = @SearchValue"
  12.  
  13.     ' Set up the sql command and lookup the parent. '
  14.     Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
  15.  
  16.         With objSqlCommand
  17.  
  18.             ' Add SqlParameters to the SqlCommand. '
  19.             .Parameters.Clear()
  20.             .Parameters.AddWithValue("@SearchValue", TextBoxParentID.Text)
  21.  
  22.             ' Open the SqlConnection before executing the query. '
  23.             Try
  24.                 ObjConnection.Open()
  25.  
  26.                 Try
  27.                     objParentNameFound = .ExecuteScalar()
  28.                     If objParentNameFound <> Nothing Then
  29.  
  30.                         ' Display the parent name here. '
  31.                         TextBoxParentsName.Text = objParentNameFound
  32.                     End If
  33.  
  34.                 Catch exSqlErrors As SqlException
  35.                     MessageBox.Show("Sorry, I couldn't execute your query because of this error: " & _
  36.                                     vbCrLf & vbCrLf & exSqlErrors.Message, _
  37.                                     "Error")
  38.                 End Try
  39.             Catch exErrors As Exception
  40.  
  41.                 MessageBox.Show("Sorry, there was an error. Details follow: " & _
  42.                                 vbCrLf & vbCrLf & exErrors.Message, _
  43.                                 "Error")
  44.             Finally
  45.                 ObjConnection.Close()
  46.             End Try
  47.         End With
  48.     End Using
  49. End If
  50.        
  51. Dim searchValue As Integer = 1
  52. Dim myConnectionString As String = "MyConnectionString"
  53. Dim sqlStatement As String = "SELECT FatherName FROM Parents WHERE ID = @SearchValue"
  54. Dim paramList(0) As SqlParameter
  55. paramList(0) = New SqlParameter() With {.Value = searchValue, .ParameterName = "@SearchValue"}
  56.  
  57. TextBoxParentsName.Text = SqlHelper.ExecuteScalar(myConnectionString, CommandType.Text, sqlStatement, paramList).ToString()