C # convert array of objects to datatable

I was unable to find an example of how to convert instances of an array of user-defined types to (D # C # ADO.Net) datatable - I want to use datatable to bind to ASP.Net data binding controls (e.g. gridview), Can anyone Anyone provide a sample or recommend me some simple samples?

Another question: do I need to convert to datatable to bind to controls in ASP.Net? Can I bind to any array of user-defined types?

thanks in advance George

+4
source share
4 answers

No, you do not need to use a DataTable for bindings - in fact, most bindings are now based on objects, especially with LINQ (which generates an object model, not a DataTable ). Just use public property names (from your class) as data elements for different columns, etc.

+3
source

I had the same requirement and found a good Pauls blog article. You can see the following link if you want it

http://weblogs.asp.net/psperanza/archive/2005/05/18/407389.aspx

Here is the code I 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 
+3
source

I would suggest using ObjectDataSource to do what you want. Then you will not need to use a DataTable at all, and you can still get the data binding. ObjectDataSource allows you to expose user-defined types to data binding, no matter how the types are obtained; they don’t need to come from the database at all if you need it.

+1
source

Regarding the comment “you cannot use LINQ for non-technical reasons”:

I assume that you do not want to use LINQ to SQL, because you want to keep your three-tier architecture. But you may not know that you can use LINQ for objects, and this will provide you with flexibility.

Suppose you have a mid-level method: List Tier2.SomeMethod (). You can assign this return value of this method as a GridView data source, and then specify SomeObject methods / properties in the GridView control: gvSomeGridView.DatasSource = Tier2.SomeMethod (); gvSomeGridView.DataBind ();

Next, you can extract SomeObject from the DataItem into GridView callbacks.

NTN.

0
source