我有这个代码:
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
加载页面时,抛出的错误是
输入数组比该表中的列数长
我的代码有什么问题?
您需要先向该数据表添加列:
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