1

I am having trouble with some code. I have created a form and all I want to do is run a query when the button is pressed and enter the outcome into the text box.

But I keep getting an error. Here is my code:

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
2
  • 2
    The error message is self-explainable. You're trying to convert a Button to a String. Replace CStr(Query) with "" and rename Query to sender. Commented Dec 15, 2014 at 11:00
  • This seems to be the event handler of a button object. In this case the Query parameter is the button pressed. Clearly this is not a string and trying to convert it to a string (CStr(Query)) is useless. Commented Dec 15, 2014 at 11:00

1 Answer 1

1

This seems to be the event handler of a button object. In this case the Query parameter is the button pressed. Clearly this is not a string and trying to convert it to a string (CStr(Query)) is useless. Instead you have your query assigned to the CommandText of the SqlCommand object.

So perhaps your code should look like this

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect!!New it was something simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.