DataReader 1 line

Lothar Rappsilber 1 Reputation point

I want the DataReader to only return one line. You can then exit. My code:

        Dim DataReader As MySqlDataReader
        DataReader = cmd.ExecuteReader()
        If DataReader.HasRows Then
            While DataReader.Read Then
                MyVariablen.Name = DataReader("Name").ToString()
            End While
        End If

Please help. I've tried a lot without success!

A set of technologies in the .NET Framework for building web applications and XML web services.
4,024 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 45,246 Reputation points

    Two options. 1) Change the While to an If. 2) Return the result after the read.

    Using DataReader As MySqlDataReader = cmd.ExecuteReader()
        If DataReader.Read Then
           MyVariablen.Name = DataReader("Name").ToString()
        End If
    End Using

    I switched to the using statement because Dim/Close is not exception safe. If a row is available then the appropriate column is read into your specified variable. If not then it remains unchanged. If you need to do something else when there are no rows then add an Else to the If block.

    0 comments No comments