vb.net让一个数组在sub中工作

时间:2018-05-02 09:50:58

标签: arrays vb.net

所以我得到了一些我希望用数据表填充数据的数组。我有一个应该填充数组的子,但是我得到了错误,Redim语句需要一个数组。这是我的代码:

这就是我在公共类中声明我的数组的方式

Public TstukkenArray(1, 0) As String 

这是我的代码,应该用数据填充数组(这是我收到错误的地方):

    '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

1 个答案:

答案 0 :(得分:0)

回顾@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