从类型'按钮'转换键入字符串无效

时间:2014-12-15 10:52:29

标签: sql vb.net

我遇到了一些代码问题。我创建了一个表单,我想要做的就是在按下按钮时运行查询并将结果输入到文本框中。

但我一直收到错误。 这是我的代码:

Public Sub getdn_Click(Query As Object, e As EventArgs) Handles getdn.Click
    Try
        SQLCon.Open()

        SQLCmd = New SqlCommand(CStr(Query), SQLCon)

        ' build the query
        SQLCmd.CommandText = "Select Top 1 docnumber+1 From transportreq Order By Docnumber Desc"
        ' run the query and obtain a reader to get the results
        Dim R As SqlDataReader = SQLCmd.ExecuteReader()

        ' check if there are results
        If (R.Read()) Then
            ' populate the values of the controls
            dnText.Text = CStr(R(0))
        End If

        SQLCon.Close()
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")

        If SQLCon.State = ConnectionState.Open Then
            SQLCon.Close()
        End If
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

这似乎是按钮对象的事件处理程序。在这种情况下,Query参数是按下的按钮。显然,这不是一个字符串,并试图将其转换为字符串(CStr(查询))是没用的。而是将您的查询分配给SqlCommand对象的CommandText。

所以也许你的代码应该是这样的

Public Sub getdn_Click(sender As Object, e As EventArgs) Handles getdn.Click
    Try
        SQLCon.Open()

        Dim Query = "Select Top 1 docnumber+1 From transportreq Order By Docnumber Desc"
        SQLCmd = New SqlCommand(Query, SQLCon)
        Dim R As SqlDataReader = SQLCmd.ExecuteReader()
        If (R.Read()) Then
            dnText.Text = CStr(R(0))
        End If

        SQLCon.Close()
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")

        If SQLCon.State = ConnectionState.Open Then
            SQLCon.Close()
        End If
    End Try
End Sub
相关问题