我正在从sql数据库中读取数据并且连接发生但发生以下错误:
{"Index was outside the bounds of the array."}
在这一行:
TextBox2.Text = TextBox2.Text & sqRdr.GetValue(22) & vbCrLf
请帮我这个,因为我已经计算了表格中的所有栏目,结果证明它们完全是(22)。
答案 0 :(得分:3)
datareader的列序号为0,因此第22列为sqRdr.GetValue(21)
答案 1 :(得分:1)
您的Datareader应如下所示,以避免在您将来增加/减少列数的情况下出现此问题....
DR["ColumnName"]
SqlDataReader的这个[字符串名称]如下所示:
Public Overrides Default ReadOnly Property Item(name As String) As Object
Get
Return Me.GetValue(Me.GetOrdinal(name))
End Get
End Property
以下是示例代码......
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