string()类型的值不能转换为字符串

时间:2017-08-17 01:49:18

标签: vb.net

我一直收到这个错误,我尽力而为但它仍然说" String的值类型()不能转换为字符串。"

以下是代码:

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

2 个答案:

答案 0 :(得分:3)

在此致电Split

TextBox2.Text = Account.Split()

您将获得String阵列。在没有参数的情况下调用Split会将String拆分为空格字符。例如,这个:

Dim arr = "Hello World".Split()

相当于:

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

Text的{​​{1}}属性类型为TextBox,因此您无法为其分配String数组。这没有意义。如果你想煎鸡蛋,你把鸡蛋盒装在锅里吗?正确的行动方案取决于您实际想要实现的目标。如果您只想在String中显示String,请执行以下操作:

TextBox

你也可以这样做:

TextBox2.Text = Account

显示包含TextBox2.Lines = Account.Split() 中不同行的元素的数组,假设您已将其TexTbox属性设置为Multiline

答案 1 :(得分:1)

TextBox2.Text是一个字符串。 string.Split()函数返回字符串的数组(由Visual Studio显示为string())。那些类型不匹配。您不能只是将数组分配给字符串。我可能会问你是否想要这个:

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

那至少会编译。但是没有意义......为什么要拆分一个字符串,只是为了再次加入它?