locked
Error when running code snippet in vb.net using max of data column in SQL Server. RRS feed

  • Question

  • User-467962651 posted

    Hi here is code snippet used temprarily on button to debug. This works but i wish to use the 2nd snippet.

    1st snippet

    Dim connString As New SqlConnection

    connString.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("sql2008r2_857000_dmcsqlConnectionString").ConnectionString

    Dim cmd As New SqlCommand("select TOP 1 no from members ORDER BY no DESC", connString)

    Dim reader As SqlDataReader

    Dim lastNumber As String

    Using (connString)

    connString.Open()

    reader = cmd.ExecuteReader()

    While reader.Read

    lastNumber = reader.Item("no")

    End While

    End Using

    Response.Write(lastNumber)

    2nd snippet

    Dim connString As New SqlConnection

    connString.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("sql2008r2_857000_dmcsqlConnectionString").ConnectionString

    Dim cmd As New SqlCommand("select max(no) from members ", connString)

    Dim reader As SqlDataReader

    Dim lastNumber As String

    Using (connString)

    connString.Open()

    reader = cmd.ExecuteReader()

    While reader.Read

    lastNumber = reader.Item("no")

    End While

    End Using

    Response.Write(lastNumber)

    1. This gives error: System.IndexOutOfRangeException: 'no' on line in bold
    2. no is a column name which has nvarchar(8) data type and allows nulls
    3. Any help would be welomed
    Monday, August 20, 2018 12:58 AM

Answers

  • User-467962651 posted

    Hi

    Now fixed thanks that link you gave pointed me in the right direction.

    I then had a problem with the max function then realised it must be given an alias in sql so it i chose max(no) as number.

    So thanks once again.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 20, 2018 2:38 PM

All replies