2013-12-14 37 views
0

我的VB.NET代碼中有錯誤。該錯誤表示statement not valid in namespace。這裏是我的代碼:聲明在命名空間錯誤中無效

Imports System.Net.Mail 
    Public Class Form1 
    End Class 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click 
     If TextBox1.Text = "" Then 
      MsgBox("Username Is Missing") 
     Exit Sub 
    Else 
    End If 
    If TextBox2.Text = "" Then 
     MsgBox("Email Is Mising") 
     Exit Sub 
    Else 
    End If 
    If TextBox3.Text = "" Then 
     MsgBox("Password Is Mising") 
     Exit Sub 
    Else 
    End If 
    Dim smtpServer As New SmtpClient() 
    Dim mail As New MailMessage() 
    smtpServer.Credentials = New Net.NetworkCredential("", "") 
    'using gmail 
    smtpServer.Port = 587 
    smtpServer.Host = "smtp.gmail.com" 
    smtpServer.EnableSsl = True 
    mail = New MailMessage() 
    mail.From = New MailAddress("") 
    mail.To.Add("") 
    mail.Subject = "Username: " & TextBox1.Text 
    mail.Body = "Username : " & TextBox1.Text & ", " & "Email: " & TextBox2.Text & ", " & "Passoword: " & TextBox3.Text 
    smtpServer.Send(mail) 
End Sub 

可有人請告訴我如何解決這個問題,如果是這樣,這將是偉大的!

+1

方法必須出現在一個類中。你寫在課外*。將'End Class'語句移到底部。 –

回答

1

你的子需要在一個類中。另外,SmtpClient和MailMessage都有.Dispose()方法,這表示它們需要被丟棄。你可以使用Using結構自動爲你做。如果在其他語句中沒有任何內容,您可以將其忽略:

Imports System.Net.Mail 
Public Class Form1 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     If TextBox1.Text = "" Then 
      MsgBox("Username Is missing") 
      Exit Sub 
     End If 

     If TextBox2.Text = "" Then 
      MsgBox("Email Is missing") 
      Exit Sub 
     End If 

     If TextBox3.Text = "" Then 
      MsgBox("Password Is missing") 
      Exit Sub 
     End If 

     Using smtpServer As New SmtpClient() 
      smtpServer.Credentials = New Net.NetworkCredential("", "") 
      'using gmail 
      smtpServer.Port = 587 
      smtpServer.Host = "smtp.gmail.com" 
      smtpServer.EnableSsl = True 

      Using mail As New MailMessage() 
       mail.From = New MailAddress("") 
       mail.To.Add("") 
       mail.Subject = "Username: " & TextBox1.Text 
       mail.Body = "Username: " & TextBox1.Text & ", " & "Email: " & TextBox2.Text & ", " & "Password: " & TextBox3.Text 
       smtpServer.Send(mail) 
      End Using 

     End Using 

    End Sub 

End Class