问题
I will have to create columns in datatable during runtime and assign values to it. How can i do it in vb.net. Any sample please...
回答1:
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
- Create Data table object.
- Add columns into that data table object.
- Add Rows with values into the object.
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
回答2:
What have you tried, what was the problem?
Creating DataColumns and add values to a DataTable is straight forward:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.
来源:https://stackoverflow.com/questions/11240245/how-to-dynamically-create-columns-in-datatable-and-assign-values-to-it