开发者

SQL possibly not returning values for a query in visual basic

In my code I enter a string in a text box and have the query check the server for the entry. If it exists it returns the string and the date into two separate variables. The database only has TrackingNumber and Date. Below is the code. As of right now i get "Invalid attempt to read when no data is present." at the "If (sdr("TrackingNumber") IsNot Nothing) Then" line. What am i doing wrong?

    Public Function CreateSqlParameter(ByVal name As String, ByVal dbType As DbType, ByVal direction As ParameterDirection, ByVal value As Object) As SqlParameter

    Dim parameter As SqlParameter = New SqlParameter()
    parameter.ParameterName = name
    parameter.DbType = dbType
    parameter.Direction = direction
    parameter.Value = value
    Return parameter

End Function




Private Sub DupOKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DupOKButton.Click


    Dim trackNumber As String
    Dim开发者_运维问答 dateSent As DateTime

    trackNumber = Me.DupTNText.Text

    Dim connectionString As String = "Data Source=XXXXX;Initial Catalog=ScannedDB;Integrated Security=True;Pooling=False;Encrypt=False"

    Dim cmdText As String = "SELECT TrackingNumber, [Date] FROM ScannedDBTable WHERE TrackingNumber = @TrackingNumber"

    Using connection As New SqlClient.SqlConnection(connectionString)

        Dim cmd As New SqlClient.SqlCommand(cmdText, connection)

        cmd.Parameters.Add(CreateSqlParameter("@TrackingNumber", DbType.String, ParameterDirection.Input, trackNumber))
        cmd.Parameters.Add(CreateSqlParameter("@Date", DbType.DateTime, ParameterDirection.Input, dateSent))

        connection.Open()

        Dim sdr As SqlDataReader = cmd.ExecuteReader()

        If (sdr("TrackingNumber") IsNot Nothing) Then
            trackNumber = Convert.ToString(sdr("@TrackingNumber"))
            dateSent = Convert.ToString(sdr("@Date"))
        Else
        End If

'Rest of code...


Your probably not getting any rows back, try:

While (sdr.read())



        If (sdr("TrackingNumber") IsNot Nothing) Then 
            trackNumber = Convert.ToString(sdr("@TrackingNumber")) 
            dateSent = Convert.ToString(sdr("@Date")) 
        Else 
        End If     

End While


Is tracking number a varchar in the database?

If so, you may need to make you VB code send an int instead of a string.


If sdr is a reader you should check for DBNull.Value.

If (sdr("TrackingNumber") IS DBNull.Value)
  'it's null
else
  'it's not null
end if

Also read to see if anything exists in your reader first. If (reader.read()) then...

If (sdr.read()) then
  if (sdr("TrackingNumber") IS DBNull.Value) Then
        'its null
  else
        'not null
  end if
end if
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜