How to return an array of class type and fill?

后端 未结 2 773
生来不讨喜
生来不讨喜 2021-01-26 10:39

I have a function which is supposed to return an array of class type.

So from database I picked data and filled datatable. Now from datatable I am picking columns value

2条回答
  •  灰色年华
    2021-01-26 11:13

    In your example there is no array where each element of the table could be stored after the transform in an AssetsDto. Moreover, you need to change from Sub to Function if you want to return anything to the caller.
    Another important change is relative to the data structure used to store the Dtos. Instead of using an array (you need to know the number of elements to effectively use it), I suggest to use a List(Of AssetsDto) where you can dynamically add elements without worrying about the size to the list.

    ' Declare as a Function that returns a List(Of AssetsDto)
    Private Function BindGridInfoFunctionalLocation() as List(Of AssetsDto)
        Dim v_ObjDs As New DataSet
    
        ' This is where we store each record transformed in an AssetsDto
        Dim result as List(Of AssetsDto) = new List(Of AssetsDto)
        Try
            v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")
    
            Dim dtTableFL As DataTable = v_ObjDs.Tables(0)
    
            ' Cycle to create the AssetsDto
            For Each Item In dtTableFL.Rows
    
                ' IMPORTANT. At each loop create a new AssetsDto, otherwise you
                ' will just change the values of the same instance 
                Dim AssetsCls As AssetsDto = new AssetsDto()
                AssetsCls.ASSETTAG = Item("TagNo")
                AssetsCls.ASSETDESC = Item("TagDescription")
                AssetsCls.PARENTTAG = Item("ParentHeirarchy")
                AssetsCls.ASSETTYPE = Item("TypeClass")
    
                ' Add the instance to the list
                result.Add(AssetsCls)
            Next
            gv_InfoFunctionalLocation.DataSource = v_ObjDs
            gv_InfoFunctionalLocation.DataBind()
        End If
    
        ' Return to caller the results
        Return results
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    

提交回复
热议问题