brain_dead_cow
brain_dead_cow

Reputation: 83

How to solve system.invalidcastexception in vb.net

Well, i have this piece of code. I want to store the contents of a textbox into an array of strings (i prefered to do it with a list of strings) and then to print each element of the array into another textbox. However when i try to compile this code i get this error message: System.InvalidCastException: 'Conversion from string "" to int is not valid' FormatException: input string is not in the correct format

Any suggestions?

Public Class NewUser

Dim textUser As String
Dim strUserName As New List(Of String)
Private Sub btnCreateUser_Click(sender As Object, e As EventArgs) Handles btnCreateUser.Click
    textUser = txtNewUser.Text
    If textUser <> "" Then
        strUserName.Add(textUser)
        txtNewUser.Clear()
    Else
        MsgBox("Username or Password is missing. Try again!")
    End If
    For Each i As String In strUserName
        TextBox1.Text = String.Join(",", strUserName(i))
    Next i
End Sub

End Class

Upvotes: 0

Views: 5230

Answers (1)

David
David

Reputation: 218798

It's not clear to me at all what you're trying to do here:

For Each i As String In strUserName
    TextBox1.Text = String.Join(",", strUserName(i))
Next i

For starters, i is a string and you're trying to use it like an integer as an index of an array. But even if you were to correct it to this:

String.Join(",", i)

That's still trying to join one string. That probably won't compile either, but even if it does it won't logically do anything. Aside from that, you're overwriting TextBox1.Text every time the loop iterates, so at best it's only ever going to equal the last value in the array.

If you're just trying to join the array into that text box, that's one line:

TextBox1.Text = String.Join(",", strUserName)

No loop required.

Upvotes: 4

Related Questions