无法绑定多部分标识符“System.Data.DataRowView”。“SQL SERVER + VB.NET

时间:2013-12-18 19:36:33

标签: sql vb.net datagridview combobox sqlcommand

您好我正在创建一个小型数据库,使用sql server作为后端,vb作为前端,我几乎已经使它工作但是我偶然发现了这个错误。

我的代码在下面提供,非常感谢一些帮助。

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim cmd As New SqlCommand
        conn = New SqlConnection(connectionstring)
        conn.Open()
        cmd = New SqlCommand("select tarif from tarif_sewa where kode_tarif = " & ComboBox1.Text & "", conn)
        TextBox2.Text = cmd.ExecuteScalar
        conn.Close()

    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您的查询的正确方法应该是

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    Using conn = New SqlConnection(connectionstring)
    Using cmd = New SqlCommand("select tarif from tarif_sewa where kode_tarif = @p1", conn)
        conn.Open()
        cmd.Parameters.AddWithValue("@p1", ComboBox1.Text)
        Dim result = cmd.ExecuteScalar
        If result IsNot Nothing Then
            ' A better conversion could be applied knowing the exact datatype of tarif '
            TextBox2.Text = result.ToString
        End If
    End Using
    End Using
End Sub

这将使用参数化查询替换字符串并置,并将您的一次性对象括在Using语句中。

但是我无法弄清楚你的代码如何发出这个错误(虽然不建议将其作为最佳实践)并非正式错误