简体   繁体   English

vb.net使数组在子中工作

[英]vb.net getting an array to work in a sub

So i got some array which i want to populate with data from a data table. 所以我得到了一些我想用数据表中的数据填充的数组。 I got a sub that should populate the array but I get the error, Redim statement requires an array. 我有一个应该填充数组的子,但出现错误,Redim语句需要一个数组。 here is my code: 这是我的代码:

this is how I declared my array in my public class 这就是我在公开课上声明数组的方式

Public TstukkenArray(1, 0) As String 

this is my code which should populate the array with the data (this is where I get the error): 这是我的代码,应该用数据填充数组(这是我收到错误的地方):

    'data from dataset to array
Sub LoadDataToArray(ds As DataSet, tablename As String, Array As Array)

    'counters 
    Dim i As Integer = 0
    Dim c As Integer = 0

    Dim arraywidth As Integer = ds.Tables(tablename).Columns.Count
    Dim arraylength As Integer = ds.Tables(tablename).Rows.Count

    'set array size
    ReDim Array(arraywidth, arraylength)

    'loop through table rows
    Do While i < ds.Tables(tablename).Rows.Count

        '
        c = 0
        'loop through columns and write data
        Do While c < ds.Tables(tablename).Columns.Count

            Array(c, i) = ds.Tables(tablename).Rows(i).Item(c)

           c = c + 1
        Loop
        i = i + 1
    Loop

End Sub

To recap comments by @jmcilhinney and @Noceo 回顾@jmcilhinney和@Noceo的评论

Public TstukkenArray(1, 0) As String
    'data from dataset to array
    'not be type Array but rather String(,)
    'try not to use type names for variables, i.e. Array
    ' if you declare a variable to be of type Array, 
    'the ReDim statement doesn't have sufficient type information to create the new array
    Sub LoadDataToArray(ds As DataSet, tablename As String, strArray(,) As String)
        'ReDim requires upper bound values, not lengths. 
        'you should be using arraywidth - 1 and arraylength - 1
        Dim arraywidth As Integer = ds.Tables(tablename).Columns.Count - 1
        Dim arraylength As Integer = ds.Tables(tablename).Rows.Count - 1
        'set array size
        ReDim strArray(arraywidth, arraylength)
        'loop through table rows
        'strongly recommend For loops rather that Do loops as well.
        For i = 0 To arraylength
            'loop through columns and write data
            For c = 0 To arraywidth
                strArray(c, i) = ds.Tables(tablename).Rows(i).Item(c).ToString
            Next
        Next
End Sub

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

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