1
votes

I have one question here regarding the String.Split to create a DataRow or specifically adding data to row in DataTable. Let say I have this:

Dim dt As New DataTable
Dim str As String = "Data1,Data2,Data3,Data4"

And I wanted to get the data from String str into the DataTable dt, split by "," .

Traditionally, I achieve this by using String.Split and this is how I do it:

Dim temp() As String = str.Split(",")

Dim dr As DataRow = dt.NewRow
dr("Col1") = temp(0)
dr("Col2") = temp(1)
dr("Col3") = temp(2)
dr("Col4") = temp(3)
dt.Rows.Add(dr)

Or

dt.Rows.Add(temp(0), temp(1), temp(2), temp(3))

This should be fine if it involve only few columns of data. What if I have like 50 columns of DataTable or even more. Is there are any steps that I could directly assign String.Split to the DataRow or DataTable.Rows. Or other method that can help me to insert the data from a String into my DataTable.

I am so sorry if any of you were unable to understand my English. Please comment for anything that was unclear and I really need guide into this as I am new to this programming world.

Thank you.

1
Just pass the array to Add. - jmcilhinney
Actually, you may not be able to pass the array, given that the parameter is type Object(). You can easily create an Object array though: temp.Cast(Of Object)().ToArray(). - jmcilhinney
What happened to dt.Rows.Add(str.Split(",")) - preciousbetine
By the way, for that code to compile, you must have Option Strict Off. Everyone should turn Option Strict On by default. - jmcilhinney
And you must make sure the number of cols in the datatable is greater than or equal to the number of items in the array. All the columns on the datatable should also be of type string - preciousbetine

1 Answers

0
votes

Thanks to @jmcilhinney for his brilliant suggestion and solution to my problem.

Actually, what I had done before is something like this

Dim dr As DataRow = str.Split(",")

And it did produce an error. That is why I thought that I were unable to directly insert an array to datatable.

Sorry for my bad. I did learn something today, as I always treat datarow he same as datatable. Because I was thinking that the datatable was the collection of datarow.

I solve this by directly adding the array to the datatable. Here are the things that I do.

Dim temp() As Object = str.Split(",")
dt.Rows.Add(temp)

Thank you all for he suggestions. I wish that @jmcilhinney had answer this by post so that I can mark it as answer. Thank you so much @jmcilhinney !!!