Sql – Invalid attempt to read data even when data is present in SqlDataReader in vb.net

sqlsql-servervb.netwinforms

Here's my code which gives error, the query returns value for the particular item.

Also in the database side the query return rows even I have put condition that if reader has rows then only assign it to a variable but still it throws an error eg.

dqty = sqlreader("qty")

Code:

Private Function checkquantity(ByVal code As String, ByVal quan As Integer) As Boolean
    sqlcommand.CommandText = "select sum(qty) as qty from pos_stock_balance where item_code='" & code & "'"
    sqlcommand.Connection = AppsCon
    sqlreader = sqlcommand.ExecuteReader
    If sqlreader.HasRows Then

        dqty = sqlreader("qty")
        sqlreader.Close()

    Else
        sqlreader.Close()
    End If
    If quan > dqty Then
        Return False
    Else
        Return True

    End If
End Function

Best Solution

It is because you are directly accessing the data without reading it, Try this,

If sqlreader.HasRows Then
      If sqlreader.read()
        dqty = sqlreader("qty")
        sqlreader.Close()
       End If
Else
       sqlreader.Close()
End If

Reference


Cleaned version of your code,

Private Function checkquantity _
(ByVal code As String, ByVal quan As Integer) As Boolean

    try

    sqlcommand.CommandText = "select" _
    & "sum(qty) as qty from pos_stock_balance where item_code='" & code & "'"

    sqlcommand.Connection = AppsCon
    sqlreader = sqlcommand.ExecuteReader

    If sqlreader.read() Then
         dqty = sqlreader("qty")
    End If

    If quan > dqty Then
        Return False
    Else
        Return True
    End If

    Finally
       sqlreader.Close()
    End try

End Function

Although i cleaned your code, Your code is still vulnerable to sql injection. Try to use parameterised queries to avoid that

Related Question