Unable to cast object of type,

时间:2015-04-29 00:17:59

标签: vb.net

This is my first post so I hope this is the right place and please be nice! Thanks.

So my issue is that I get an error while downloading a file. I have made a downloader app to download a specific file. It runs just fine until it hits the download complete event.

Here is the code:

Private Sub cmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDownload.Click


    Try
        Dim webClient As New WebClient()
        AddHandler webClient.DownloadProgressChanged, AddressOf client_ProgressChanged
        AddHandler webClient.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
        webClient.DownloadFileAsync(New Uri("https://dl.dropbox.com/s/wtdagv0xvliwvv2/viruslist.dat?dl=0"), Application.StartupPath + "\viruslist.dat")
    Catch ex As Exception

    End Try
End Sub

Public Sub client_ProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)
    Try
        Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
        Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
        Dim percentage As Double = bytesIn / totalBytes * 100
        ProgBar.Value = Integer.Parse(Math.Truncate(percentage).ToString())
        Label3.Text = "Total Complete " + ProgBar.Value.ToString + " %"
    Catch ex As Exception

    End Try
End Sub

Public Sub client_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadDataCompletedEventArgs)
    MessageBox.Show("Database has finished downloading!", "Download Finished...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Sub

The error I get is an

Unhandled Exception: System.InvalidCastException: Unable to cast object to type 'System.ComponentModel.AsyncCompletedEventArgs' to type 'System.Net DownloadDataCompletedEventArgs', at Database_Download.frm.Main._Lambda$__1(Object a0. AsyncCompletedEventArgs a1)

Like I said all runs fine until it needs to fire the DownloadComplete, but it does not say my messagebox at all it just pops this error. I don't understand this because I have done this exact code in other projects without problems. Please help!

1 个答案:

答案 0 :(得分:0)

Change the signature. MSDN documentation

Public Sub client_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
   MessageBox.Show("Database has finished downloading!", "Download Finished...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Sub