2014-09-20 84 views
1

作爲一個新手,我越來越老試圖找出如何返回一個字符串值從一個SQL選擇命令與VB代碼背後。我有的程序如下。基本上我想要做的就是提取表格BuildFields中的DisplayName字段中的值(帶有WHERE條件),並將其放置到formview模板中的標籤的文本字段中。看起來應該不難,我確信我錯過了一些東西。有沒有人有任何想法或看到我做錯了什麼?這不會返回任何東西。謝謝。從sql select命令返回字符串值vb.net代碼背後

Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound 

    Dim dt As New DataTable() 
    Dim conCString As String = ConfigurationManager.ConnectionStrings("conCString").ConnectionString 
    Dim lbl As Label = FormView1.FindControl("Label1") 
    Dim sqlConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conCString").ConnectionString) 
    Dim cmd As New SqlCommand 

    cmd.CommandText = "SELECT [DisplayName] FROM [BuildFields] WHERE ([TableID] = N'Capacitors') AND (ColumnID = N'UserField01') ORDER BY [ColumnID]" 
    cmd.CommandType = CommandType.Text 
    cmd.Connection = SqlConnection 

    Try 
     SqlConnection.Open() 
     Dim result As String 

     result = cmd.ExecuteScalar() 

     lbl.Text = result 

     sqlConnection.Close() 
    Catch ex As Exception 

    End Try 

End Sub 
+0

可能的重複http://stackoverflow.com/questions/10856686/need-to-get-value-from-sql-query – 2014-09-20 16:15:03

回答

0

打開Option strictON現在。爲什麼?如果/當ExecuteScalar返回DBNull時會發生什麼?

我敢打賭,如果你刪除try-catch塊,那麼你會得到這樣的錯誤信息:

「」類型的未處理的異常出現在Microsoft.VisualBasic.dll中

這裏是你的代碼應該如何看起來像:

Dim result As Object 
result = cmd.ExecuteScalar() 
lbl.Text = If((TypeOf result Is String), CType(result, String), "(null)") 

你也應該使用打交道時的Using關鍵字一次性物品。

Using sqlConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("conCString").ConnectionString) 
    Using cmd As New SqlCommand() 
     'Code goes here... 
    End Using 
End Using 

而且你永遠不應該吞下這樣的異常。始終採取適當的行動和/或重新拋出錯誤。

Catch ex As Exception 
    'Do something or else: 
    Throw 
End Try