简体   繁体   中英

Weird array issue…need advice on this

I am reading data from an sql database and the connection happens but the following error occurs:

 {"Index was outside the bounds of the array."}

On this line:

 TextBox2.Text = TextBox2.Text & sqRdr.GetValue(22) & vbCrLf

Please help me with this as I have counted all the columns in my table and they have turned out to be exactly (22).

datareader的列序号为0,因此第22 sqRdr.GetValue(21)

Your Datareader should be like below to avoid this issue in a case when you have increased/decreased the number of column in future....

DR["ColumnName"]

SqlDataReader's this[string name] looks like:

Public Overrides Default ReadOnly Property Item(name As String) As Object
    Get
        Return Me.GetValue(Me.GetOrdinal(name))
    End Get
End Property

Below is the sample code...

Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
    con.Open()
    Dim cmd As New SqlCommand()
    Dim expression As String = "Parameter value"
    cmd.CommandType = CommandType.StoredProcedure
    cmd.CommandText = "Your Stored Procedure"
    cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
    cmd.Connection = con
    Using dr As IDataReader = cmd.ExecuteReader()
                'You code like ....dr["YourColumnName"]
        If dr.Read() Then
        End If
    End Using
End Using

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