简体   繁体   中英

Visual Studio 2013 sql data reader

I'm only starting out with this. I've been over numerous tutorials but I just can't get this to work. I'm trying to fill a text box with a result but it is not working. I've even put in a MsgBox("AA") to check that the reader has rows and the msgbox appears but still it does not fill the textbox with the value.

Option Explicit On
Option Strict On
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class CustEnquiry
Private Sub TextBox_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
        Dim connectionString As String = _
            "Data Source=SERVER;Initial Catalog=DATABASE;" _
            & "Persist Security Info=True;User ID=USERID;Password=PASSWORD"
        Using connection As New SqlConnection(connectionString)
            Dim command As SqlCommand = New SqlCommand( _
           "SELECT FIELD FROM dbo.TABLE WHERE VALUE = '092902D';", _
           connection)
            connection.Open()
            Dim reader As SqlDataReader = command.ExecuteReader()
            If reader.HasRows Then
                MsgBox("AA")
                TextBox2.Text = reader.GetString(0)
            End If
            reader.Close()
        End Using
    End Sub
End Class

reader.Read()

i know that is short but that is the answer

You have to advance the reader to the next(first) record, therefore use Read :

If reader.HasRows Then
    reader.Read()
    MsgBox("AA")
    TextBox2.Text = reader.GetString(0)
End If

HasRows just returns if there are records, it does not advance the reader. You could also use Read to check if there's at least one record in the result set.

If reader.Read() Then
    MsgBox("AA")
    TextBox2.Text = reader.GetString(0)
End If

Since you are selecting and expecting only a single value you could also use SqlCommand.ExecuteScalar instead of the reader:

Dim field As Object = command.ExecuteScalar() ' is DbNull.Value if the field is null in the database '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM