William Juden
William Juden

Reputation: 35

Value of type string() cannot be converted to string

I keep getting this error, I tried all I could but it still says "Value type of String() cannot be converted to string."

Here is the code:

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click

End Sub
Sub New()
    InitializeComponent()

    RAN = New Random
    WB = New WebClient


End Sub

Private Const IDNum As String = "https://example.com/Data.php"

Private WB As WebClient
Private RAN As Random

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim Account As String() = WB.DownloadString(IDNum).Split(Environment.NewLine)
    AccSplit(Account(RAN.Next(1, Account.Length)))

End Sub


Private Sub AccSplit(ByVal Account As String)

    TextBox2.Text = Account.Split()
End Sub

Upvotes: 2

Views: 15882

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

When you call Split here:

TextBox2.Text = Account.Split()

You are getting a String array back. Calling Split with no arguments will split the String on whitespace characters. For instance, this:

Dim arr = "Hello World".Split()

is equivalent to this:

Dim arr = {"Hello", "World"}

The Text property of a TextBox is type String, so you can't assign a String array to it. That doesn't make sense. If you want to fry an egg, do you put am egg carton in the pan? The correct course of action depends on what you're actually trying to achieve. If you just want that String displayed in the TextBox then do this:

TextBox2.Text = Account

You could also do this:

TextBox2.Lines = Account.Split()

to display the array with the elements on separate lines in the TexTbox, which assumes that you have set its Multiline property to True.

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

TextBox2.Text is a string. The string.Split() function returns an array of strings (shown by Visual Studio as a string()). Those types don't match up. You can't just assign an array to a string. I might ask if you wanted this:

TextBox2.Text = String.Join(",", Account.Split())

That will at least compile. But it makes no sense... why split a string, just to join it back again?

Upvotes: 1

Related Questions