I am learning to code since a few months.
Today I want to code a password manager. Everything works fine but the get icon function has problem if a host is unreachable. This function is to get the favicon from the webpage.
For Each myItem As ListViewItem In lv_data.Items
Dim baseurl = myItem.Text
Dim url As Uri = New Uri(baseurl)
If url.HostNameType = UriHostNameType.Dns Then
Dim iconURL = "http://" & url.Host & "/favicon.ico"
Dim request As System.Net.WebRequest = System.Net.HttpWebRequest.Create(iconURL)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream()
lv_data.Items.Item(myItem.Index).ImageIndex = myItem.Index
Catch ex As WebException
Remote host could not be resolved
First move the try catch inside the loop
For Each myItem As ListViewItem In lv_data.Items Try Dim baseurl = myItem.Text Dim url As Uri = New Uri(baseurl) ... Catch End Try Next
This will allow your code to continue inside the foreach loop when it encounters an exception in retrieving the favicon.ico
The next problem is how you address the images in the imagelist. When you encounter the exception because your code cannot retrieve the favicon you don't add anything to the ImageList.
At this point your ImageList and your ListView.Items don't contain the same number of elements, thus you cannot use the
myItem.Index to reference the image in the ImageList.
But, because the image has been just added to the ImageList in the previous line, then you are certain that the image required is the last element of the ImageList. So you can use the
ImageList.Images.Count property (less 1)
imglist.Images.Add(Image.FromStream(stream)) myItem.ImageIndex = imgList.Images.Count - 1
(Notice that you can use directly myItem in this context)