update label & listbox while sending email

Greenmet29

Member
Joined
Apr 29, 2010
Messages
9
Programming Experience
1-3
I am new to vb.net, and I have finished developing this app except for one thing: When it finishes a loop (sending an email for each file in a directory) it doesn't update the label or the listbox. Whats funny about it is that it does update the progress bar. Any ideas?

VB.NET:
IMports System.Net.Mail
Imports System.IO
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim numFiles As Integer = System.IO.Directory.GetFiles("c:\email").Length()
        lblEmailTotal.Text = numFiles
    End Sub

    Private Sub btnShowFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowFiles.Click
        Dim di As New IO.DirectoryInfo("c:\email")
        Dim aryFi As IO.FileInfo() = di.GetFiles("*.txt")
        Dim fi As IO.FileInfo
        Dim numFiles As Integer = System.IO.Directory.GetFiles("c:\email").Length()
        lblEmailTotal.Text = numFiles
        Dim smtpServer As New SmtpClient()
        Dim mail As New MailMessage()
        smtpServer.Credentials = New Net.NetworkCredential("myemail@email.com", "mypassword")
        smtpServer.Port = 123
        smtpServer.Host = ("smtp.server.com")
        smtpServer.EnableSsl = True

        Dim sent As Integer = 0

        For Each fi In aryFi
            mail = New MailMessage()
            mail.From = New MailAddress("myemail@email.com")
            Dim File As StreamReader = New StreamReader(fi.FullName)
            Dim myLine As String


            Dim fileArray(3) As String
            Dim i As Integer = 0

            For i = 0 To 2
                myLine = File.ReadLine()
                fileArray(i) = myLine
            Next
            lbxText.Items.Add(fileArray(0))
            lbxText.Items.Add(fileArray(1))
            lbxText.Items.Add(fileArray(2))
            lbxText.Items.Add(" ")
            mail.To.Add(fileArray(0))
            mail.Subject = fileArray(1)
            mail.Body = fileArray(2)
            smtpServer.Send(mail)
            sent += 1
            Dim perc As Integer = (sent / numFiles) * 100
            lblEmailSent.Text = sent
            ProgressBar1.Value = perc
            mail = Nothing
        Next

    End Sub
End Class
 
I suggest you use the SendAsync method. Use a new SmtpClient instance for each message to send, ie declare it within the loop.
 
Back
Top