为什么我收到错误“输入数组比此表中的列数长”?

问题描述 投票:0回答:1

我有这个代码:

Public Function comb1(ByVal SName As String) As DataTable

        Dim dt As New DataTable
        cmd = New SqlCommand("Select Distinct RName from tb_RS_New", con)
        dr2 = cmd.ExecuteReader
        While (dr2.Read())
            dt.Rows.Add(dr2("RName"))
        End While
        Return dt

End Function

加载页面时,抛出的错误是

输入数组比该表中的列数长

我的代码有什么问题?

c# vb.net
1个回答
22
投票

您需要先向该数据表添加列:

Dim dt As New DataTable
dt.Columns.Add("RName", GetType(String))

另外,我对代码中的

con
cmd
dr2
变量了解不多,但我强烈建议您正确处置它们:

Dim dt As New DataTable
dt.Columns.Add("RName", GetType(String))

Using con As New SqlConnection("connection string to the database")
    Using cmd = con.CreateCommand()
        con.Open()
        cmd.CommandText = "Select Distinct RName from tb_RS_New"
        Using dr = cmd.ExecuteReader()
            While (dr.Read())
                dt.Rows.Add(dr("RName"))
            End While
        End Using
    End Using
End Using
© www.soinside.com 2019 - 2024. All rights reserved.