- Looking for the best way to use ExecuteScalar()
- Dim objParentNameFound As Object
- TextBoxParentsName.Text = ""
- If TextBoxParentID.Text <> "" Then
- ' Display the parent's name using the parent ID. '
- Dim strSqlStatement As String = "Select FatherName " & _
- "From Parents " & _
- "Where ID = @SearchValue"
- ' Set up the sql command and lookup the parent. '
- Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
- With objSqlCommand
- ' Add SqlParameters to the SqlCommand. '
- .Parameters.Clear()
- .Parameters.AddWithValue("@SearchValue", TextBoxParentID.Text)
- ' Open the SqlConnection before executing the query. '
- Try
- ObjConnection.Open()
- Try
- objParentNameFound = .ExecuteScalar()
- If objParentNameFound <> Nothing Then
- ' Display the parent name here. '
- TextBoxParentsName.Text = objParentNameFound
- End If
- Catch exSqlErrors As SqlException
- MessageBox.Show("Sorry, I couldn't execute your query because of this error: " & _
- vbCrLf & vbCrLf & exSqlErrors.Message, _
- "Error")
- End Try
- Catch exErrors As Exception
- MessageBox.Show("Sorry, there was an error. Details follow: " & _
- vbCrLf & vbCrLf & exErrors.Message, _
- "Error")
- Finally
- ObjConnection.Close()
- End Try
- End With
- End Using
- End If
- Dim searchValue As Integer = 1
- Dim myConnectionString As String = "MyConnectionString"
- Dim sqlStatement As String = "SELECT FatherName FROM Parents WHERE ID = @SearchValue"
- Dim paramList(0) As SqlParameter
- paramList(0) = New SqlParameter() With {.Value = searchValue, .ParameterName = "@SearchValue"}
- TextBoxParentsName.Text = SqlHelper.ExecuteScalar(myConnectionString, CommandType.Text, sqlStatement, paramList).ToString()