ar.dll
ar.dll

Reputation: 787

vb.net convert array element into string

Using the code below to loop through my array which was created by reading a text file with 10 or so lines in it, so each thing in the array is one of those lines from the text file

Dim myarray As Array
myarray = Split(stringfromtextfile, vbCrLf)
For each element in myArray
MgBox(element)
Dim splititem As String = Split(element, "\")

The message box shows the line as I'm expecting but when I try to split it up I just get the error:

Error 1 Value of type '1-dimensional array of String' cannot be converted to 'String'.

How do I get the value which was shown in the message box converted to a string to I can then do a split on it?

Cheers!

Upvotes: 1

Views: 9016

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460028

I would use .NET methods instead of VB6 methods which are not strongly typed, hence less efficient and - more important - error-prone and less readable.

For example with LINQ:

Dim first10LineFields = From line In System.IO.File.ReadLines(path)
                        Let fields = line.Split("\"c)
                        Select fields
                        Take 10

Output:

For Each lineFields  As String() In first10LineFields 
    Dim fieldsCommaSeparated = String.Join(",", lineFields)
    MessageBox.Show(fieldsCommaSeparated)
Next

Upvotes: 2

Cody Gray
Cody Gray

Reputation: 244692

This line of code is invalid:

Dim splititem As String = Split(element, "\")

The Split function returns an array of strings, but you're trying to assign the result to a variable that represents only a single string.

That's what the error message is telling you: the "value of type '1-dimensional array of String'" is what is being returned from the Split function, and that "cannot be converted to 'String'" in order to store it in the splititem variable.

Change it to look like this (note the parentheses, which indicate an array of String):

Dim splititem As String() = Split(element, "\")

And do strongly consider using the .NET Framework methods for string manipulation, rather than the old VB 6 methods. They are provided primarily for compatibility purposes with older code, not intended for use in new code.

If you actually are writing VB 6 code (which is what this looks like), rather than VB.NET code, you cannot assign variables at the point of their declaration. You'll need to split these up into separate statements:

Dim splititem As String()
splititem = Split(element, "\")

Upvotes: 3

Related Questions