Reputation: 45771
I failed to find a sample about how to convert an array instances of user defined types into a (C# ADO.Net) datatable -- I want to use the datatable to bind to ASP.Net data bound controls (e.g. gridview). Could anyone provide a sample or recommend me to some simple samples?
Another question is, whether it is a must to convert to datatable in order to bound to controls in ASP.Net? Could I bound to any array of user defined types?
thanks in advance, George
Upvotes: 4
Views: 14259
Reputation: 471
I had the same requirement and I found a nice article at Pauls Blog. You can have a look at the following link if you still wanted it
http://weblogs.asp.net/psperanza/archive/2005/05/18/407389.aspx
Here is the code that I have used in my project. Hope that helps
Public Function ConvertArrayToDatatable(ByVal arrList As ArrayList) As DataTable
Dim dt As New DataTable
Try
If arrList.Count > 0 Then
Dim arrype As Type = arrList(0).GetType()
dt = New DataTable(arrype.Name)
For Each propInfo As PropertyInfo In arrype.GetProperties()
dt.Columns.Add(New DataColumn(propInfo.Name))
Next
For Each obj As Object In arrList
Dim dr As DataRow = dt.NewRow()
For Each dc As DataColumn In dt.Columns
dr(dc.ColumnName) = obj.GetType().GetProperty(dc.ColumnName).GetValue(obj, Nothing)
Next
dt.Rows.Add(dr)
Next
End If
Return dt
Catch ex As Exception
Return dt
End Try
End Function
Upvotes: 3
Reputation: 51
In regards to the comment "can not use LINQ for non-technical reasons":
I presume you don't want to use LINQ to SQL since you want to maintain your three-tiered architecture. But you may not know that you can use LINQ to Objects and that would provide the flexibility you seek.
Suppose you have a middle tier method: List Tier2.SomeMethod(). You can assign that return value of that method as the GridView data source and then specify SomeObject methods/properties in the GridView control: gvSomeGridView.DatasSource = Tier2.SomeMethod(); gvSomeGridView.DataBind();
Further you can then retrieve SomeObject from the DataItem in GridView callbacks.
HTH.
Upvotes: 0
Reputation: 21836
I would suggest using the ObjectDataSource class to do what you want. Then you won't need to use a DataTable at all, and you'll still be able to get data binding. ObjectDataSource allows you to expose user defined types to data binding, and it doesn't matter how the types are obtained; they don't need to come from a database at all, if that's what you need.
Upvotes: 1
Reputation: 1062780
No, you don't need a DataTable
to do binding - in fact, most binding now is object based, especially with LINQ (which generates an object model, not a DataTable
). Just use the public property names (from your class) as the data-members for different columns, etc.
Upvotes: 3