Private ReadOnly bytesReceivedById As New Dictionary(Of Integer, Long)
Private totalBytesToReceive As Long
Private ReadOnly table As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New SqlDataAdapter("SQL query here", "connection string here")
adapter.Fill(table)
End Using
table.Columns.Add("Image", GetType(Byte()))
DataGridView1.DataSource = table
'Start a download for each row.
For Each row As DataRow In table.Rows
Dim client As New WebClient
'Handle pertinent events.
AddHandler client.DownloadProgressChanged, AddressOf WebClient_DownloadProgressChanged
AddHandler client.DownloadDataCompleted, AddressOf WebClient_DownloadDataCompleted
'Identify each download with the record ID.
client.DownloadDataAsync(New Uri(CStr(row("URL"))), row("ID"))
Next
End Sub
Private Sub WebClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
'Update the progress on the UI thread.
BeginInvoke(New Action(Of Integer, Long, Long)(AddressOf UpdateProgress),
{CInt(e.UserState), e.BytesReceived, e.TotalBytesToReceive})
End Sub
Private Sub WebClient_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
'Update the DataTable on the UI thread because it is bound to a DataGridView, which is a control.
BeginInvoke(New Action(Of Integer, Byte())(AddressOf SetImage),
{CInt(e.UserState), e.Result})
Dim client = DirectCast(sender, WebClient)
'Unregister event handlers.
RemoveHandler client.DownloadProgressChanged, AddressOf WebClient_DownloadProgressChanged
RemoveHandler client.DownloadDataCompleted, AddressOf WebClient_DownloadDataCompleted
End Sub
Private Sub UpdateProgress(id As Integer, bytesReceived As Long, totalBytesToReceive As Long)
If Not bytesReceivedById.ContainsKey(id) Then
'This is the first progress event for this download.
bytesReceivedById.Add(id, bytesReceived)
Me.totalBytesToReceive += totalBytesToReceive
Else
'Update progress for existing download.
bytesReceivedById(id) = bytesReceived
End If
'Calculate the percentage for all downloads combined.
Dim progressPercent = bytesReceivedById.Values.Sum() / Me.totalBytesToReceive * 100L
ProgressBar1.Value = CInt(progressPercent)
End Sub
Private Sub SetImage(id As Integer, img As Byte())
Dim row = table.Rows.Find(id)
row("Image") = img
End Sub