我尝试使用VB.NET创建一个小程序。
打开时,会在网页下方显示网页和进度条。当用户单击网页中的链接时,progess栏将停止处理并显示You clicked a link
消息。处理完成后,会显示另一条消息:Thanks for helping me
。
我在VB.NET中编写了整个过程的代码,但是当我调试它时会显示一条消息:
'0'的值对'index'无效。 'index'应介于0和-1之间。 参数名称:index
我的代码是:
Public Class MyPage
Private Sub MyPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Interval = 1500
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Document.Links(0).AttachEventHandler("onclick", AddressOf LinkClick)
End Sub
Sub LinkClick(ByVal sender As Object, ByVal e As System.EventArgs)
Timer1.Start()
MsgBox("You clicked the link", , "Clicked The link")
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
ProgressBar1.Increment(2)
If ProgressBar1.Value = 100 Then
Timer1.Stop()
ProgressBar1.Value = 0
MsgBox("Thanks for help me", , "Thankssss!")
End If
End Sub
End Class
我该如何解决这个问题?
答案 0 :(得分:3)
你盲目地假设页面总是有一个链接。错误的假设。修正:
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If WebBrowser1.Document.Links.Count > 0 Then
WebBrowser1.Document.Links(0).AttachEventHandler("onclick", AddressOf LinkClick)
End If
End Sub
或者根据用途,更明白:
For Each link As HtmlElement In WebBrowser1.Document.Links
link.AttachEventHandler("onclick", AddressOf LinkClick)
Next