简体   繁体   English

奇怪的阵列问题......需要建议

[英]Weird array issue…need advice on this

I am reading data from an sql database and the connection happens but the following error occurs: 我正在从SQL数据库中读取数据并且连接发生但发生以下错误:

 {"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). 请帮我这个,因为我已经计算了表格中的所有列,结果证明它们完全是(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.... 如果您将来增加/减少列数,您的Datareader应如下所示,以避免此问题....

DR["ColumnName"]

SqlDataReader's this[string name] looks like: SqlDataReader的这个[字符串名称]如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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