Convert Array of Objects to Data Table

yuzhangqi發表於2010-12-20

Normally in a web application, the Presentation Layer retrieves an Array/Collection of business objects as the data source to bind to GridView control. However sometimes we do need a DataTable to return. In such cases we need convert an Array/Collection of object to a DataTable.

Now let's look into te code.

[C#]

public DataTable ConvertArrayToTable(Array myList)
{
DataTable dt = new DataTable();
if (myList.Length > 0)
{
PropertyInfo[] propInfos = myList.GetValue(0).GetType().GetProperties();

foreach (PropertyInfo propInfo in propInfos)
{
dt.Columns.Add(propInfo.Name, propInfo.PropertyType);
}

foreach (object tempObject in myList)
{
DataRow dr = dt.NewRow();

for (int i = 0; i < propInfos.Length; i++)
{
dr[i] = propInfos[i].GetValue(tempObject, null);
}

dt.Rows.Add(dr);
}
}

return dt;
}

[VB.NET]

Public Shared Function ConvertArrayToDataTable(ByVal list As ArrayList) As DataTable
Dim table As New DataTable()

If list.Count > 0 Then
Dim iterator As IEnumerator = list.GetEnumerator()
iterator.MoveNext()
Dim propInfos As PropertyInfo() = iterator.Current.GetType().GetProperties()

For Each propInfo As PropertyInfo In propInfos
table.Columns.Add(propInfo.Name, propInfo.PropertyType)
Next

For Each obj As Object In list
Dim row As DataRow = table.NewRow()

For i As Int32 = 0 To propInfos.Count - 1
row.Item(i) = propInfos(i).GetValue(obj, Nothing)
Next

table.Rows.Add(row)
Next

End If

Return table
End Function

References

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/13651903/viewspace-1043351/,如需轉載,請註明出處,否則將追究法律責任。

相關文章