VB.Net/Development/Regular Expressions

Материал из VB Эксперт
Перейти к: навигация, поиск

Demonstrating Class Regex

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim myMatch As Match
      " create regular expression
      Dim expression As Regex = _
         New Regex("J.*\d[0-35-9]-\d\d-\d\d")
      Dim string1 As String = "05-12-75" & _
         vbCrLf & "11-04-68" & vbCrLf & _
         "04-28-73" & vbCrLf & _
         "12-17-77"
      " match regular expression to string and  
      " print out all matches
      For Each myMatch In expression.Matches(string1)
         Console.WriteLine( myMatch.ToString() )
      Next
  End Sub " Main
End Class


Regular Expressions Match

 
Imports System
Imports System.Text.RegularExpressions
Public Class MainClass
   Shared Sub Main()
        Dim pattern As String = "g"
        Dim AString As String = "a string"
        
        Dim reg_exp As New Regex(pattern)
        Dim matches As MatchCollection
        
        matches = reg_exp.Matches(AString)
        Console.WriteLine(AString)
        
        For Each a_match As Match In matches
            Console.WriteLine("Index " & a_match.Index)
            Console.WriteLine("Length " & a_match.Length)
        Next a_match
   End Sub 
End Class


Regular Expressions: Validate Address

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      If Not Regex.Match("Address", "^[0-9]+\s+([a-zA-Z]" & _
         "+|[a-zA-Z]+\s[a-zA-Z]+)$").Success Then
         " address was incorrect
         Console.WriteLine("Invalid Address")
      End If
  End Sub " Main
End Class


Regular Expressions: Validate City

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      If Not Regex.Match("City", "^([a-zA-Z]+|[a-zA-Z]" & _
         "+\s[a-zA-Z]+)$").Success Then
         " city was incorrect
         Console.WriteLine("Invalid City")
      End If
  End Sub " Main
End Class


Regular Expressions: Validate Name

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      If Not Regex.Match("asdfdsa", _
         "^[A-Z][a-zA-Z]*$").Success Then
         " last name was incorrect
         Console.WriteLine("Invalid Last Name")
      End If
  End Sub " Main
End Class


Regular Expressions: validate Phone Number

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      If Not Regex.Match("111-111-1111", "^[1-9]" & _
         "\d{2}-[1-9]\d{2}-\d{4}$").Success Then
         " phone was incorrect
         Console.WriteLine("Invalid Phone Number")
         Return
      End If
  End Sub " Main
End Class


Regular Expressions: Validate Zip Code

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      If Not Regex.Match("zipcode", "^\d{5}$").Success Then
         " zip code was incorrect
         Console.WriteLine("Invalid zip code")
         Return
      End If
  End Sub " Main
End Class


==Regular to parse time: /td>



 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    
    Shared Sub Main()
             Dim string1 As String = _
              "04:03:27 127.0.0.0 www.vbex.ru"
             " time = one or more digits or colons
             " followed by a space
             " ip address = one or more digits or dots
             " followed by space
             " site = one or more characters
             Dim regString As String = "(?<time>(\d|\:)+)\s" & _
             "(?<ip>(\d|\.)+)\s" & _
             "(?<site>\S+)"
             Dim theReg As New Regex(regString)
             Dim theMatches As MatchCollection = theReg.Matches(string1)
             Dim theMatch As Match
             For Each theMatch In theMatches
                 If theMatch.Length <> 0 Then
                     Console.WriteLine( _
                         "theMatch: {0}", _
                         theMatch.ToString(  ))
                     Console.WriteLine( _
                         "time: {0}", _
                        theMatch.Groups("time"))
                     Console.WriteLine( _
                          "ip: {0}", _
                         theMatch.Groups("ip"))
                     Console.WriteLine( _
                          "site: {0}", _
                         theMatch.Groups("site"))
                 End If
             Next theMatch
   End Sub
End Class


Strip tags from HTML to create Text version of a web page

  
Public Class MainClass
    Public Shared Sub Main()
        System.Console.WriteLine(StripTags(GetPageHTML("http://www.g.ru/")))
    End Sub
    Public Shared Function StripTags(ByVal HTML As String) As String
        Return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "")
    End Function
    Public Shared Function GetPageHTML(ByVal URL As String) As String
        Dim objWC As New System.Net.WebClient()
        Return New System.Text.UTF8Encoding().GetString(objWC.DownloadData(URL))
    End Function
End Class


TextBox validation: validate in KeyPressed Event

 
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class MainClass
    
    Shared Sub Main()
        Dim form1 As Form = New Form1
        Application.Run(form1)

    End Sub
End Class
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        "This call is required by the Windows Form Designer.
        InitializeComponent()
        "Add any initialization after the InitializeComponent() call
    End Sub
    "Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents txtFirstName As System.Windows.Forms.TextBox
    Friend WithEvents txtLastName As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents errProvider As System.Windows.Forms.ErrorProvider
    Friend WithEvents txtEmail As System.Windows.Forms.TextBox
    Friend WithEvents Label3 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.GroupBox1 = New System.Windows.Forms.GroupBox()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.txtFirstName = New System.Windows.Forms.TextBox()
        Me.txtLastName = New System.Windows.Forms.TextBox()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.errProvider = New System.Windows.Forms.ErrorProvider()
        Me.txtEmail = New System.Windows.Forms.TextBox()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.GroupBox1.SuspendLayout()
        Me.SuspendLayout()
        "
        "GroupBox1
        "
        Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label3, Me.txtEmail, Me.Label2, Me.Label1, Me.txtFirstName, Me.txtLastName})
        Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(368, 124)
        Me.GroupBox1.TabIndex = 11
        Me.GroupBox1.TabStop = False
        "
        "Label2
        "
        Me.Label2.Location = New System.Drawing.Point(16, 52)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(64, 16)
        Me.Label2.TabIndex = 8
        Me.Label2.Text = "Last Name:"
        "
        "Label1
        "
        Me.Label1.Location = New System.Drawing.Point(16, 28)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(64, 16)
        Me.Label1.TabIndex = 7
        Me.Label1.Text = "First Name:"
        "
        "txtFirstName
        "
        Me.txtFirstName.Location = New System.Drawing.Point(84, 24)
        Me.txtFirstName.Name = "txtFirstName"
        Me.txtFirstName.Size = New System.Drawing.Size(152, 21)
        Me.txtFirstName.TabIndex = 4
        Me.txtFirstName.Text = ""
        "
        "txtLastName
        "
        Me.txtLastName.Location = New System.Drawing.Point(84, 48)
        Me.txtLastName.Name = "txtLastName"
        Me.txtLastName.Size = New System.Drawing.Size(152, 21)
        Me.txtLastName.TabIndex = 5
        Me.txtLastName.Text = ""
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(152, 204)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(76, 24)
        Me.Button1.TabIndex = 10
        Me.Button1.Text = "OK"
        "
        "txtEmail
        "
        Me.txtEmail.Location = New System.Drawing.Point(84, 84)
        Me.txtEmail.Name = "txtEmail"
        Me.txtEmail.Size = New System.Drawing.Size(152, 21)
        Me.txtEmail.TabIndex = 9
        Me.txtEmail.Text = ""
        "
        "Label3
        "
        Me.Label3.Location = New System.Drawing.Point(16, 88)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(64, 16)
        Me.Label3.TabIndex = 10
        Me.Label3.Text = "Email:"
        "
        "ErrorProviderValidation
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 14)
        Me.ClientSize = New System.Drawing.Size(388, 238)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.GroupBox1, Me.Button1})
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Name = "ErrorProviderValidation"
        Me.Text = "ErrorProvider Validation"
        Me.GroupBox1.ResumeLayout(False)
        Me.ResumeLayout(False)
    End Sub
#End Region
 

    Private Sub txtEmail_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtEmail.KeyPress
        Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")
        If Expression.IsMatch(CType(sender, TextBox).Text) Then
            errProvider.SetError(sender, "")
        Else
            errProvider.SetError(sender, "Not a valid email.")
        End If
    End Sub
End Class


Use Regex to match

 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    
    Shared Sub Main()
             Dim string1 As String = "This is a test string"
             Dim theReg As New Regex("(\S+)\s")
             Dim theMatches As MatchCollection = theReg.Matches(string1)
             Dim theMatch As Match
             For Each theMatch In theMatches
                 Console.WriteLine("theMatch.Length: {0}", _
                    theMatch.Length)
                 If theMatch.Length <> 0 Then
                     Console.WriteLine("theMatch: {0}", _
                        theMatch.ToString(  ))
                 End If
             Next theMatch
           
   End Sub
End Class


Use Regex to separate strings

 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    
    Shared Sub Main()
             Dim s1 As String = "One,Two,Three"
             Dim theRegex As New Regex(" |, |,")
             Dim sBuilder As New StringBuilder(  )
             Dim id As Integer = 1
             Dim subString As String
             For Each subString In theRegex.Split(s1)
                 id = id + 1
                 sBuilder.AppendFormat("{0}: {1}"  _
                   & Environment.NewLine, id, subString)
             Next subString
             Console.WriteLine("{0}", sBuilder.ToString(  ))
            
   End Sub
End Class


Use Regular Expressions to parse IP address

 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    
    Shared Sub Main()
             Dim string1 As String = _
              "04:03:27 127.0.0.0 www.vbex.ru"
             " time = one or more digits or colons
             " followed by a space
             " ip address = one or more digits or dots
             " followed by space
             " site = one or more characters
             Dim regString As String = "(?<time>(\d|\:)+)\s" & _
             "(?<ip>(\d|\.)+)\s" & _
             "(?<site>\S+)"
             Dim theReg As New Regex(regString)
             Dim theMatches As MatchCollection = theReg.Matches(string1)
             Dim theMatch As Match
             For Each theMatch In theMatches
                 If theMatch.Length <> 0 Then
                     Console.WriteLine( _
                         "theMatch: {0}", _
                         theMatch.ToString(  ))
                     Console.WriteLine( _
                         "time: {0}", _
                        theMatch.Groups("time"))
                     Console.WriteLine( _
                          "ip: {0}", _
                         theMatch.Groups("ip"))
                     Console.WriteLine( _
                          "site: {0}", _
                         theMatch.Groups("site"))
                 End If
             Next theMatch
   End Sub
End Class


Use Regular Expressions to Split String

 
Imports System
Imports System.Text 
Imports System.Text.RegularExpressions
Public Class MainClass
    Shared Sub Main(ByVal args As String())
             Dim s1 As String = "One,Two,Three"
             Dim theRegex As New Regex(" |, |,")
             Dim sBuilder As New StringBuilder( )
             Dim id As Integer = 1
             Dim subString As String
             For Each subString In theRegex.Split(s1)
                 id = id + 1
                 sBuilder.AppendFormat("{0}: {1}"  _
                   & Environment.NewLine, id, subString)
             Next subString
             Console.WriteLine("{0}", sBuilder)
    End Sub
End Class


Use Regular Expression to Validate Email address

 
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class MainClass
    
    Shared Sub Main()
        Dim form1 As Form = New Form1
        Application.Run(form1)

    End Sub
End Class
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        "This call is required by the Windows Form Designer.
        InitializeComponent()
        "Add any initialization after the InitializeComponent() call
    End Sub
    "Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents txtFirstName As System.Windows.Forms.TextBox
    Friend WithEvents txtLastName As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents errProvider As System.Windows.Forms.ErrorProvider
    Friend WithEvents txtEmail As System.Windows.Forms.TextBox
    Friend WithEvents Label3 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.GroupBox1 = New System.Windows.Forms.GroupBox()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.txtFirstName = New System.Windows.Forms.TextBox()
        Me.txtLastName = New System.Windows.Forms.TextBox()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.errProvider = New System.Windows.Forms.ErrorProvider()
        Me.txtEmail = New System.Windows.Forms.TextBox()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.GroupBox1.SuspendLayout()
        Me.SuspendLayout()
        "
        "GroupBox1
        "
        Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label3, Me.txtEmail, Me.Label2, Me.Label1, Me.txtFirstName, Me.txtLastName})
        Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(368, 124)
        Me.GroupBox1.TabIndex = 11
        Me.GroupBox1.TabStop = False
        "
        "Label2
        "
        Me.Label2.Location = New System.Drawing.Point(16, 52)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(64, 16)
        Me.Label2.TabIndex = 8
        Me.Label2.Text = "Last Name:"
        "
        "Label1
        "
        Me.Label1.Location = New System.Drawing.Point(16, 28)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(64, 16)
        Me.Label1.TabIndex = 7
        Me.Label1.Text = "First Name:"
        "
        "txtFirstName
        "
        Me.txtFirstName.Location = New System.Drawing.Point(84, 24)
        Me.txtFirstName.Name = "txtFirstName"
        Me.txtFirstName.Size = New System.Drawing.Size(152, 21)
        Me.txtFirstName.TabIndex = 4
        Me.txtFirstName.Text = ""
        "
        "txtLastName
        "
        Me.txtLastName.Location = New System.Drawing.Point(84, 48)
        Me.txtLastName.Name = "txtLastName"
        Me.txtLastName.Size = New System.Drawing.Size(152, 21)
        Me.txtLastName.TabIndex = 5
        Me.txtLastName.Text = ""
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(152, 204)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(76, 24)
        Me.Button1.TabIndex = 10
        Me.Button1.Text = "OK"
        "
        "txtEmail
        "
        Me.txtEmail.Location = New System.Drawing.Point(84, 84)
        Me.txtEmail.Name = "txtEmail"
        Me.txtEmail.Size = New System.Drawing.Size(152, 21)
        Me.txtEmail.TabIndex = 9
        Me.txtEmail.Text = ""
        "
        "Label3
        "
        Me.Label3.Location = New System.Drawing.Point(16, 88)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(64, 16)
        Me.Label3.TabIndex = 10
        Me.Label3.Text = "Email:"
        "
        "ErrorProviderValidation
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 14)
        Me.ClientSize = New System.Drawing.Size(388, 238)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.GroupBox1, Me.Button1})
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Name = "ErrorProviderValidation"
        Me.Text = "ErrorProvider Validation"
        Me.GroupBox1.ResumeLayout(False)
        Me.ResumeLayout(False)
    End Sub
#End Region
 

    Private Sub txtEmail_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtEmail.KeyPress
        Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")
        If Expression.IsMatch(CType(sender, TextBox).Text) Then
            errProvider.SetError(sender, "")
        Else
            errProvider.SetError(sender, "Not a valid email.")
        End If
    End Sub
End Class


Use Regx.split to split string

 
Imports System
Imports System.Text
Imports System.Text.RegularExpressions

Public Class MainClass
    
    Shared Sub Main()
             Dim s1 As String = "One,Two,Three"
             Dim sBuilder As New StringBuilder(  )
             Dim id As Integer = 1
             Dim subString As String
             For Each subString In Regex.Split(s1, " |, |,")
                 id = id + 1
                 sBuilder.AppendFormat("{0}: {1}" _
                   & Environment.NewLine, id, subString)
             Next subString
             Console.WriteLine("{0}", sBuilder.ToString(  ))
           
   End Sub
End Class


Using Regex method Replace: ^

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim testString1 As String = "This sentence ends in 5 stars *****"
      Dim testString2 As String = "1, 2, 3, 4, 5, 6, 7, 8"
      Dim testRegex1 As Regex = New Regex("stars")
      Dim testRegex2 As Regex = New Regex("\d")
      
      Console.WriteLine("Original String 1" & vbTab & _
         vbTab & vbTab & testString1)
      testString1 = Regex.Replace(testString1, "\*", "^")
      Console.WriteLine("^ substituted for *" & vbTab & _
         vbTab & vbTab & testString1)
  End Sub " Main
End Class


Using Regex method Replace: by another string

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim testString1 As String = "This sentence ends in 5 stars *****"
      Dim testString2 As String = "1, 2, 3, 4, 5, 6, 7, 8"
      Dim testRegex1 As Regex = New Regex("stars")
      Dim testRegex2 As Regex = New Regex("\d")
      
      Console.WriteLine("Original String 1" & vbTab & _
         vbTab & vbTab & testString1)
      testString1 = testRegex1.Replace(testString1, "carets")
      Console.WriteLine("""carets"" substituted for " & _
         """stars""" & vbTab & testString1)
  End Sub " Main
End Class


Using Regex method Replace:First 3 digits replaced

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim testString1 As String = "This sentence ends in 5 stars *****"
      Dim testString2 As String = "1, 2, 3, 4, 5, 6, 7, 8"
      Dim testRegex1 As Regex = New Regex("stars")
      Dim testRegex2 As Regex = New Regex("\d")
      
      Console.WriteLine("Original String 2" & _
         vbTab & vbTab & vbTab & testString2)
      Console.WriteLine("First 3 digits replaced by " & _
         """digit""" & vbTab & _
         testRegex2.Replace(testString2, "digit", 3))
  End Sub " Main
End Class


Using Regex method Replace: String split at commas

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim testString1 As String = "This sentence ends in 5 stars *****"
      Dim testString2 As String = "1, 2, 3, 4, 5, 6, 7, 8"
      Dim testRegex1 As Regex = New Regex("stars")
      Dim testRegex2 As Regex = New Regex("\d")
      Dim resultString As String
      
      Console.WriteLine("String split at commas" & vbTab & _
         vbTab & "[")
       
      For Each resultString In Regex.Split(testString2, ",\s*")
         Console.WriteLine("""" & resultString & """, ")
      Next
  End Sub " Main
End Class


Using Regex method Replace:\w+

 
Imports System.Text.RegularExpressions
Imports System
Public Class MainClass
   Shared Sub Main()
      Dim testString1 As String = "This sentence ends in 5 stars *****"
      Dim testString2 As String = "1, 2, 3, 4, 5, 6, 7, 8"
      Dim testRegex1 As Regex = New Regex("stars")
      Dim testRegex2 As Regex = New Regex("\d")
      
      Console.WriteLine("Original String 1" & vbTab & _
         vbTab & vbTab & testString1)
      Console.WriteLine("Every word replaced by " & _
         """word""" & vbTab & _
         Regex.Replace(testString1, "\w+", "word"))
  End Sub " Main
End Class


Validate TextBox: cannot be empty

 
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class MainClass
    
    Shared Sub Main()
        Dim form1 As Form = New Form1
        Application.Run(form1)

    End Sub
End Class
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        "This call is required by the Windows Form Designer.
        InitializeComponent()
        "Add any initialization after the InitializeComponent() call
    End Sub
    "Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents txtLastName As System.Windows.Forms.TextBox
    Friend WithEvents txtFirstName As System.Windows.Forms.TextBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.txtLastName = New System.Windows.Forms.TextBox()
        Me.txtFirstName = New System.Windows.Forms.TextBox()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.GroupBox1 = New System.Windows.Forms.GroupBox()
        Me.GroupBox1.SuspendLayout()
        Me.SuspendLayout()
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(152, 204)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(76, 24)
        Me.Button1.TabIndex = 6
        Me.Button1.Text = "OK"
        "
        "txtLastName
        "
        Me.txtLastName.Location = New System.Drawing.Point(84, 48)
        Me.txtLastName.Name = "txtLastName"
        Me.txtLastName.Size = New System.Drawing.Size(152, 21)
        Me.txtLastName.TabIndex = 5
        Me.txtLastName.Text = ""
        "
        "txtFirstName
        "
        Me.txtFirstName.Location = New System.Drawing.Point(84, 24)
        Me.txtFirstName.Name = "txtFirstName"
        Me.txtFirstName.Size = New System.Drawing.Size(152, 21)
        Me.txtFirstName.TabIndex = 4
        Me.txtFirstName.Text = ""
        "
        "Label1
        "
        Me.Label1.Location = New System.Drawing.Point(16, 28)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(64, 16)
        Me.Label1.TabIndex = 7
        Me.Label1.Text = "First Name:"
        "
        "Label2
        "
        Me.Label2.Location = New System.Drawing.Point(16, 52)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(64, 16)
        Me.Label2.TabIndex = 8
        Me.Label2.Text = "Last Name:"
        "
        "GroupBox1
        "
        Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label2, Me.Label1, Me.txtFirstName, Me.txtLastName})
        Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(368, 88)
        Me.GroupBox1.TabIndex = 9
        Me.GroupBox1.TabStop = False
        "
        "SimpleValidation
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 14)
        Me.CausesValidation = False
        Me.ClientSize = New System.Drawing.Size(384, 238)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.GroupBox1, Me.Button1})
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Name = "SimpleValidation"
        Me.Text = "SimpleValidation"
        Me.GroupBox1.ResumeLayout(False)
        Me.ResumeLayout(False)
    End Sub
#End Region
    Private Sub txtName_Validating(ByVal sender As Object, ByVal e As System.ruponentModel.CancelEventArgs) Handles txtFirstName.Validating, txtLastName.Validating
        If CType(sender, TextBox).Text = "" Then
            MessageBox.Show("You have to type something.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            e.Cancel = True
        End If
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class