1
此代碼有效。它基於我在互聯網上找到的一些代碼。尋找使用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
感謝您的答覆。我會看看Microsoft Access應用程序,看看我是否可以從中學習。如果你有時間,你能展示一些代碼塊來幫助進一步擴展將代碼分離到其他方法嗎? – 2012-02-27 14:48:50