3

The result of my sql-query is a single value i want display that in a lable but dont know how. I have a solution creating a dataset put the result of the query into that dataset and get it by row(0),column(0) but i guess there is a smarter way doing it.

Private myquery As String

Sub New(ByVal query As String)
    myquery = query
End Sub
Public Sub query_Send()
    Dim myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
    Dim mycmd As SqlCommand = New SqlCommand(Me.myQuery, myconn)
    Dim myTable As New DataTable
    Dim previousConnectionState As ConnectionState = myconn.State
    Try
        If myconn.State = ConnectionState.Closed Then
            myconn.Open()
            Dim myDA As New SqlDataAdapter(mycmd)
            myDA.Fill(myTable)
            tb.text = **...**
        End If
        If previousConnectionState = ConnectionState.Closed Then
            myconn.Close()
        End If
    End Try
End Sub
0

2 Answers 2

8

You can use SqlCommand.ExecuteScalar Method

Dim querystr as String = "select value from MyTable where ID=5"
Dim mycmd As New SqlCommand(querystr, connection)
dim value as Object = mycmd.ExecuteScalar()

The value you can put to your textbox. ExecuteScalar returns first value of first row of the resultset (equivalent of row(0).column(0) ) When no record is returned the value is nothing.

1
  • works for me, thanks CODE Dim sql As String Dim cmd As New OleDb.OleDbCommand con.Open() sql = "SELECT MAX(pos) FROM rac" cmd.Connection = con cmd.CommandText = sql Dim value As Object = cmd.ExecuteScalar Me.TextBox6.Text = value + 1
    – IvanS
    Commented Apr 25, 2020 at 21:10
0

Try something more along the lines of:

    Using myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
        Dim myDA As New SqlDataAdapter()
        myDA.SelectCommand = New SqlCommand(myQuery, myconn)
        myDA.Fill(myTable)
        Return myTable 
    End Using 

Or you can just get ahold of the first item in the first row with

myTable.Rows(0).ItemArray(0).ToString()

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.