14

I'm using vb.net / winforms. How can I convert 10 lines with three columns into a DataSet/DataTable?

Lines are something like this:

Item-1, $100, 44

Item-2, $42, 3

etc

2 Answers 2

30
Dim Table1 As DataTable
Table1 = New DataTable("TableName")

Dim column1 As DataColumn = New DataColumn("Column1")
column1.DataType = System.Type.GetType("System.String")

Dim column2 As DataColumn = New DataColumn("Column2")
column2.DataType = System.Type.GetType("System.Int32") 
Dim column3 As DataColumn = New DataColumn("Column2")
column3.DataType = System.Type.GetType("System.Int32")

Table1.Columns.Add(column1)
Table1.Columns.Add(column2)
Table1.Columns.Add(column3)


Dim Row1 As DataRow
Row1 = Table1.NewRow()

Row1.Items("Column1") = "Item1"
Row1.Items("Column2") = 44
Row1.Items("Column3") = 99

Table1.Rows.Add(Row1)

' Repeat for other rows
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Need to update column3 definition: Dim column3 As DataColumn = New DataColumn("Column3")
I had to use Row1.Item("Column1") = "Item1" instead of Items() for some reason, but I was able to get it to work.
24

I know this post is old, but I believe this can be solved in fewer lines of code.

' Declare DataTable
Dim Table1 As new DataTable()
' Define columns
Table1.Columns.Add("Column1", GetType(System.String))
Table1.Columns.Add("Column2", GetType(System.Int32))
Table1.Columns.Add("Column3", GetType(System.Int32))
' Add a row of data
Table1.Rows.Add("Item1", 44, 99)
Table1.Rows.Add("Item2", 42, 3)

Source DotNetPerls.com : VB.NET DataTable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.