Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create columns in datatable and assign values to it?

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...

like image 558
Anuya Avatar asked Jun 28 '12 07:06

Anuya


2 Answers

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")
like image 151
RKK Avatar answered Nov 16 '22 11:11

RKK


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.

like image 43
Tim Schmelter Avatar answered Nov 16 '22 11:11

Tim Schmelter