How to: Object Array Convert to Table (DATATABLE)
Author: water like smoke (http://blog.9cbs.net/lzmtw)
Date:
2005-4-15
Sometimes we want to display the contents of the array on the DataGrid. How to do it, MSDN said about DataGrid, "You can also bind DataGrid to arraylist.arraylist, which can contain multiple types of objects, but all items in the list have the same When the type, DataGrid can only bind to such a list. This means that all objects must be the same type, or must inherit from the same class as the first item in the list. For example, if the first item in the list is Control The second item may be TextBox (it inherited from Control). On the other hand, if the first item is TextBox, the second object cannot be Control. In addition, ArrayList must contain items when binding. Empty ArrayList It will cause empty grid. When bind to ArrayList, set the DataGridTableStyle's mappingName to "ArrayList". The relevant examples have, just the specific source, I forgot. Another method is provided below that the array is converted to an object array (if it is already a group of object arrays), then convert to a table (DataTable). Of course, according to my habits, the conversion method is definitely universal.
First, sample data
Use a group of data that represents the basic information of the student. Data Significance: Name, Learn, Gender, Age. (The following data is similar, purely coincident, do not leave the temple)
Ma Xiaofei, A001005, 15, male
Just Xiaowei, A002008, 14, male
Xue Sai, A002004, 16, female
East, A001002, 15, male
Wang Cangyue, A002009, 15, female
Second, build the corresponding class (object)
Public Class StudentBase
PUBLIC Name as String
Publicology AS String
PUBLIC Age As INTEGER
PUBLIC Gender AS String
END CLASS
Why is the above definition? It is mainly to show convenient to DataGrid. In order to facilitate the conversion of the array to an object array, we build a class again:
Public Class Student PUBLIC CLASS
Private _items (-1) as studentbase 'This is the number of objects you want to use.
Public Readonly Property Items () as studentbase ()
Get
Return_Items
END GET
End Property
Public Sub Add (Byval Name As String, Byval Age AS Integer, Byval SEX AS STRING) Add a student
Dim mitem as new studentbase
With mitem
Name = Name
Learn = NO
Age = age
Gender = SEX
End with
DIM I as integer = _items.length
Redim preserve _items (i)
_Items (i) = mitement sub
END CLASS
Third, convert the sample data into an object array
Dim Mstudent As New Student
WITH MSTUDENT
.Add ("Ma Xiaofei", "A001005", 15, "Men")
.Add ("Gang Xiaowei", "A002008", 14, "Men")
.Add ("Xue Sai", "A002004", 16, "Female")
.Add ("East Light", "A001002", 15, "Men")
.Add ("Wang Cangyue", "A002009", 15, "Female")
End with
Fourth, transform the object array into a table (DataTable) static class
Public Class ArrayTATIBLE
Private shared _columns as datacolumn ()
Private shared _items as object ()
Private shared _table as dataable
Private shared _tablename as string
'This static class is only open, returns a DataTable
Public Shared Function Convert (Byval Items As Object ()) AS DataTable
_Table = Nothing
_Items = items
IF _Items is nothing orelse _items.length = 0 THEN RETURN NOTING
'Do a reference to generate DATATABLE with the first item of an object array
IF not getDataColumn (_Items (0) .gettype) THEN RETURN NOTHING
AddRow ()
Return_Table
END FUNCTION
"Generate a DataTable based on Item information
Private shared function getDatacolumn (byval t as type) as boolean
If t.GETFIELDS.LENGTH = 0 THEN RETURN FALSE
Redim _Column (T.Getfields.Length)
'Takenamed Table name
_TABLENAME = T.toString.substring (t.toString.lastIndexof (" " c) 1)
'Add a sequence number. Can you make a selection number, I added it here.
DIM C as datacolumn
c = new datacolumn
With C
.Columnname = "serial number"
.DATATYPE = GetType (Integer)
.Autoincrement = true
.Autoincrementseed = 1
End with
_COLUMNS (0) = C
'Share information
DIM I as integer = 0
Dim f as system.reflection.fieldInfo
For Each F in T.Getfields
c = new datacolumn
i = 1
With C
.Columnname = f.name
.DATATYPE = F.fieldType
_COLUMNS (I) = C
End with
NEXT
'Creating a Table instance_table = new dataable (_tablename)
_Table.columns.addrange (_COLUMNS)
Return True
END FUNCTION
'Traversing an array of objects, and each item is added to DataTable as a line.
Private shared sub addrow ()
DIM O as Object
Dim f as system.reflection.fieldInfo
For Each O in _Items
DIM R AS DATAROW = _table.newrow
For Each F IN O.gettype.Getfields
R (f.name) = F.GetValue (O)
NEXT
_Table.Rows.Add (r)
NEXT
_Table.acceptchanges ()
End Sub
END CLASS
5. Try it.
DIM TABLE AS DATATABLE
Table = arraytotable.convert (mstudent.Items)
Me.DataGrid1.datasource = TABLE
Me.DataGrid1.captionText = Table.tablename
The following is all code. If there is a mistake on your IDE, it is the reason for the wrap space, and it will be broken.
Public Class Form1
Inherits System.Windows.Forms.form
#Region "Windows Form Designer Generated Code"
Public Sub New ()
Mybase.new ()
'This call is required for the Windows Form Designer.
InitializeComponent ()
'Add any initialization after INITIALIZECOMPONENT ()
End Sub
'Form rewriting Dispose to clean up the list of components.
Protected Overloads Overrides Sub Dispose (Byval Disposing as Boolean)
IF Disposing then
IF not (Components Is Nothing) THEN
Components.dispose ()
END IF
END IF
Mybase.dispose (Disposing)
End Sub
'Windows Form Designer
Private Components as System.comPonentModel.icontainer
'Note: The following process is necessary for the Windows Form Designer.
'You can modify this process using the Windows Form Designer.
'Don't modify it using the code editor.
Friend Withevents Button1 As System.Windows.Forms.Button
Friend Withevents DataGrid1 As System.Windows.Forms.DataGrid
Me.Button1 = new system.windows.Forms.Button
Me.DataGrid1 = new system.windows.forms.DataGrid
Ctype (me.datagrid1, system.componentmodel.isupportinitialize) .beginInit ()
Me.suspendlayout ()
'
'Button1
'
Me.Button1.Anchor = CType (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.button1.location = new system.drawing.point (40, 32)
Me.Button1.name = "button1"
Me.button1.size = new system.drawing.size (248, 40)
Me.Button1.tabindex = 0
Me.Button1.text = "button1"
'
'DataGrid1
'
Me.DataGrid1.datamember = ""
Me.DataGrid1.HeaderforeColor = system.drawing.systemcolors.ControlText
Me.DataGrid1.location = new system.drawing.point (48, 120)
Me.DataGrid1.name = "DataGrid1"
Me.DataGrid1.size = new system.drawing.size (528, 344)
Me.DataGrid1.tabindex = 1
'
'Form1
'
Me.autoscalebasesize = new system.drawing.size (6, 14)
Me.ClientSize = new system.drawing.size (632, 533)
Me.Controls.add (me.datagrid1)
Me.Controls.add (me.button1)
Me.KeyPreview = TRUE
Me.Name = "Form1"
Ctype (me.datagrid1, system.componentmodel.isupportinitialize) .endinit ()
Me.ResumeLayout (false)
End Sub
#End region
Private sub button1_click (byvale as system.object, byval e as system.eventargs) Handles Button1.click
Dim Mstudent As New Student
WITH MSTUDENT
.Add ("Ma Xiaofei", "A001005", 15, "Men")
.Add ("Gang Xiaowei", "A002008", 14, "Men")
.Add ("Xue Sai", "A002004", 16, "Female")
.Add ("East Light", "A001002", 15, "Men")
.Add ("Wang Cangyue", "A002009", 15, "Female")
End with
DIM TABLE AS DATATABLE
Table = arraytotable.convert (mstudent.Items)
Me.DataGrid1.datasource = TABLE
Me.DataGrid1.captionText = Table.tablename
End Sub
END CLASS
Public Class StudentBase
PUBLIC Name as String
Publicology AS String
PUBLIC Age As INTEGER
PUBLIC Gender AS String
END CLASS
Public Class Student PUBLIC CLASS
Private _items (-1) as studentbase 'This is the number of objects you want to use.
Public Readonly Property Items () as studentbase ()
Get
Return_Items
END GET
End Property
Public Sub Add (Byval Name As String, Byval Age AS Integer, Byval SEX AS STRING) Add a student
Dim mitem as new studentbase
With mitem
Name = Name
Learn = NO
Age = age
Gender = SEX
End with
DIM I as integer = _items.length
Redim preserve _items (i)
_Items (i) = mitem
End Sub
END CLASS
Public Class ArrayTATIBLE
Private shared _columns as datacolumn ()
Private shared _items as object ()
Private shared _table as dataable
Private shared _tablename as string
'This static class is only open, returns a DataTable
Public Shared Function Convert (Byval Items As Object ()) AS DataTable
_Table = Nothing
_Items = items
IF _Items is nothing orelse _items.length = 0 THEN RETURN NOTING
'Do a reference to generate DATATABLE with the first item of an object array
IF not getDataColumn (_Items (0) .gettype) THEN RETURN NOTHING
AddRow ()
Return_Table
END FUNCTION
"Generate a DataTable based on Item information
Private shared function getDatacolumn (byval t as type) as boolean
If t.GETFIELDS.LENGTH = 0 THEN RETURN FALSE
Redim _Column (T.Getfields.Length)
'Takenamed Table name
_TABLENAME = T.toString.substring (t.toString.lastIndexof (" " c) 1)
'Add a sequence number. Can you make a selection number, I added it here.
DIM C as datacolumn
c = new datacolumn
With C
.Columnname = "serial number"
.DATATYPE = GetType (Integer)
.Autoincrement = true
.Autoincrementseed = 1
End with
_COLUMNS (0) = C
'Share information
DIM I as integer = 0
Dim f as system.reflection.fieldInfofor Each F in t.Getfields
c = new datacolumn
i = 1
With C
.Columnname = f.name
.DATATYPE = F.fieldType
_COLUMNS (I) = C
End with
NEXT
'Creating a Table instance
_Table = New DataTable (_TABLENAME)
_Table.columns.addrange (_COLUMNS)
Return True
END FUNCTION
'Traversing an array of objects, and each item is added to DataTable as a line.
Private shared sub addrow ()
DIM O as Object
Dim f as system.reflection.fieldInfo
For Each O in _Items
DIM R AS DATAROW = _table.newrow
For Each F IN O.gettype.Getfields
R (f.name) = F.GetValue (O)
NEXT
_Table.Rows.Add (r)
NEXT
_Table.acceptchanges ()
End Sub
END CLASS