2014-11-04 96 views
0

该程序加载一个.txt将它拆分为“:”,然后将其分别检查到某处 每当我的程序到达列表末尾时出现错误这是我的代码VB.net索引超出范围异常

Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click 
    If ListBox1.Items.Count = 0 Then 
     MsgBox("Checking DONE") 
    ElseIf ListBox1.Items.Count.ToString > 0 Then 

     Dim str As String 
     Dim strArr() As String 

     str = ListBox1.Items(0) 
     strArr = str.Split(":") 
     If str.Count > 0 Then 
      WebBrowser1.Document.GetElementById("email").SetAttribute("value", (strArr(0))) 
      WebBrowser1.Document.GetElementById("password").SetAttribute("value", (strArr(1))) 
      WebBrowser1.Document.GetElementById("login-form-contBtn").InvokeMember("click") 
      WaitForPageLoad() 
      Threading.Thread.Sleep(5000) 
      Me.Button2.PerformClick() 
     Else 
      MsgBox("Done") 
     End If 
     End If 


End Sub 

另外,Me.Button2.PerformClick()点击按钮编程,然后按钮两次点击这个按钮,它应该继续下去,直到列表框为空,但它只是崩溃/给出错误

以下是错误http://gyazo.com/cb7c47bca69af101871035bf18231b6e

这是将列表导入列表框的按钮。 OpenFileDialog1.Filter =“Text Files(* .txt)|”| * .TXT” OpenFileDialog1.ShowDialog()

Dim R As New IO.StreamReader(OpenFileDialog1.FileName) 
    Dim string1 As String() = R.ReadToEnd().Split(New String(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) 

    ListBox1.Items.AddRange(string1) 
    R.Close() 
    ListBox1.SelectedItem = ListBox1.Items(0) 

    Dim str As String 
    Dim strArr() As String 

    str = ListBox1.SelectedItem 
    strArr = str.Split(":") 'Delimits the imported combo list 
    Label4.Text = (strArr(0)) 'Email 
    Label3.Text = (strArr(1)) 'Password 
    Label6.Text = (ListBox1.Items.Count) 'How big is combo? 

回答

1

您在strArr分裂str但你检查str.Count

str = ListBox1.Items(0) 
strArr = str.Split(":") 
If strArr.Count > 0 Then 
    .... 

下面的代码使用strArr的索引0和索引1所以最好检查

If strArr.Count > 1 Then 
+0

谢谢!!! lol,为什么索引1而不是0 ?,只是想增加我的知识 – 2014-11-04 17:29:28

+0

每个数组在NET中在索引0处开始。在strArr中分割字符串Count表示数组中存在的元素的数量,因此字符串XXXXX:YYYYY在拆分时变为两个元素数组strArr(0)= XXXX,strArr(1) = YYYYY。如果没有:(XXXXXYYYYY),你仍然从分割中得到一个数组,但它是一个单元数组(strArr(0)= XXXXYYYYY)。如果你尝试在这个数组上使用index = 1,你会得到一个异常,因为索引1处没有元素。 – Steve 2014-11-04 17:45:12

+0

仍然不明白,但是谢谢你的帮助:) – 2014-11-04 18:03:27