从sql select命令返回字符串值后面的vb.net代码

时间:2014-09-20 15:37:15

标签: .net vb.net

作为一个新手,我正在逐渐变老,试图弄清楚如何从带有vb代码的sql select命令返回一个字符串值。我的程序如下。基本上我要做的是在表BuildFields(带有WHERE条件)的DisplayName字段中提取值,并将其放入formview模板中标签的文本字段中。它似乎不应该是困难的,我确信我错过了一些东西。有没有人有任何想法或看到我做错了什么?这不会返回任何东西。感谢。

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

1 个答案:

答案 0 :(得分:1)

立即启用Option strict 开启。为什么?如果ExecuteScalar返回DBNull时会发生什么?

我敢打赌,如果删除try-catch块,则会收到以下错误消息:

  

Microsoft.VisualBasic.dll中出现未处理的“System.InvalidCastException”类型异常

以下是您的代码的外观:

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