Imports System.Data.SqlClient
Imports System.Web.Configuration

Partial Class ReadDatabase
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim reader As SqlDataReader
        Dim studentId As Integer = 0

        ' Set the content type
        Response.ContentType = "text/plain"
        Response.ContentEncoding = Encoding.UTF8

        ' Prevent page from being cached when we are polling
        ' Without this we just keep reading the same data
        ' from the Browser cache. At least that's what
        ' happened to me.
        Response.Expires = -1

        Try
            connection = New SqlConnection(WebConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString)
            command = New SqlCommand("SELECT * FROM Names", connection)

            Using connection
                connection.Open()
                reader = command.ExecuteReader()

                If reader.HasRows Then
                    ' Create a HTML table containing the database
                    ' rows we are reading.
                    Response.Write("<table border='1'>")
                    Do While reader.Read()
                        ' Add a HTML table row per database row
                        Response.Write("<tr>")
                        ' Each database field has it's own HTML table column
                        Response.Write("<td>" & CType(reader("Name"), String) & "</td>")
                        Response.Write("</tr>")
                    Loop
                    ' Close the HTML table once we've read all 
                    ' the database rows
                    Response.Write("</table>")
                Else
                    Response.Write("No names in database")
                End If

                connection.Close()
            End Using
        Catch
            Response.Write("An error occurred")
        End Try
    End Sub
End Class
