deephect deephect - 3 months ago 43
Vb.net Question

Loop with Webbrowser VB.Net

dim web1 as string
dim web2 as string
dim i as int32

web1 = "www.webaddress1.com"
web2 = "www.webaddress2.com"
web3 = "www.webaddress3.com"

i = 1

while i < 100

webbrowser1.navagate(web1)

i = i + 1

end while


I have a number of websites not sure how to get the website to change at the beginning of each loop, so it will go through web1 web2 web3 etc.

Answer

Right now, all your code is doing is going to the same website 99 times. You aren't passing the website variable anything new. Like Plutonix said, you need to iterate through a collection, that would look something like this:

    Dim lstWebsites As New List(Of String) From {"www.webaddress1.com", _
                                                 "www.webaddress2.com", _
                                                 "www.webaddress3.com"}
    For Each website As String In lstWebsites
        webbrowser1.navigate(New Uri(website))
    Next

Be careful though, a loop like that is going to execute very quickly, so depending on what you are hitting those links for, you might want to space them out with a timer, or execute each one after the DocumentCompleted event


EDIT-response to comment: If I were doing this in my own project, I would prefer using the DocumentCompleted event instead of a timer, that way the process takes as little time as possible to finish running and each address visited is given all the time it needs to finish loading. That said, in principle, that would look something like this:

Public Class Form1
    Private Property lstWebsites As List(Of String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lstWebsites = New List(Of String) From {"www.webaddress1.com", _
                                                "www.webaddress2.com", _
                                                "www.webaddress3.com"}
        NavigateNext()
    End Sub

    Private Sub NavigateNext()
        If lstWebsites IsNot Nothing AndAlso lstWebsites.Count > 0 Then
            WebBrowser1.Navigate(New Uri(Me.lstWebsites(0)))
            lstWebsites.RemoveAt(0)
        Else
            Me.Close()
        End If
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        NavigateNext()
    End Sub
End Class
Comments