Converting a list of BO to DataTable using CopyToDataTable (System.Data.DataSetExtensions)

Converting a list of BO to DataTable using CopyToDataTable (System.Data.DataSetExtensions)

Old forum URL: forums.lhotka.net/forums/t/4465.aspx


skaue posted on Thursday, March 06, 2008

Has anyone used this before? I tried to search for info on this here, but no luck. Maybe it's a bad idea, but all I really want to do is simply get a DataTable out of a readonlylist.

-Tommy

JoeFallon1 replied on Thursday, March 06, 2008

I had to build a DataTable from a ROC in order to bind it to a chart.
(Technically the ROC could be bound to the chart but I wanted to add some logic to the process so I built the dt.)

You should be able to do something similar.

Private Function GetData() As DataTable
  Dim dt As New DataTable()
 
Dim row As DataRow = dt.NewRow()
 
Dim currDate As String = mFilteredList.Item(0).Mydate
 

  'Build a list of unique code values 
  Dim
codeList As New System.Collections.Generic.List(Of String)

  
For Each info As MyROC.MyInfo In mFilteredList
   
If Not codeList.Contains(info.Code) Then
     
codeList.Add(info.Code)
   
End If
 
Next

  'Create the columns for each unique code
 
dt.Columns.Add("Series Label", GetType(String))

  For Each code As String In codeList
    dt.Columns.Add(code,
GetType(Decimal))
 
Next

  row.Item(0) = CDate(mFilteredList.Item(0).Mydate).ToString("MMM dd, yyyy") 'Series Label

  For i As Integer = 0 To mFilteredList.Count - 1
    mInfo = mFilteredList.Item(i)
   
If currDate <> mInfo.Mydate Then
     
'add the row with values to the dt
     
dt.Rows.Add(row)
     
'then create a new row and assign the date to the series label
     
row = dt.NewRow()
      row.Item(0) =
CDate(mInfo.Mydate).ToString("MMM dd, yyyy") 'Series Label
    
currDate = mInfo.Mydate
   
End If

    'assign the value to the column with the same name as code
   
row.Item(mInfo.Code) = mInfo.Myvalue
 
Next

  'add the last row
 
dt.Rows.Add(row)

  Return dt
End Function

Joe

skaue replied on Thursday, March 06, 2008

Thanks for your input. I started to write code to convert manually to DataTable, but I then started to search for a way so that I didn't have to write a load of code on every BO.... I found a "attribute+reflection"-way, but I was hoping that this could be done from the System.Data namespace.

-Tommy

Copyright (c) Marimer LLC