我尝试使用 VB.NET 制作一个小程序。
当它打开时,它会在网页下方显示一个网页和一个进程栏。当用户单击网页中的链接时,进度栏将停止处理并显示You clicked a link
消息。处理完成后,它会显示另一条消息,内容为:Thanks for helping me
。
我在 VB.NET 中编写了整个过程的代码,但是当我调试它时,它会显示一条消息:
值"0"对"索引"无效。"索引"应介于 0 和 -1 之间。 参数名称:索引
我的代码是:
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
如何解决此问题?
你盲目地假设页面将始终有一个链接。 错误的假设。 修复:
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