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

Anuya picture Anuya · Jun 28, 2012 · Viewed 113.2k times · Source

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

Answer

RKK picture RKK · Jun 28, 2012

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")