WHAT'S NEW?
Loading...

Create pattern with Regular Expression in VB.Net


Create your own patter with regular expression in Visual Basic.Net. In order to create a regular expression pattern, first declared Imports System.Text.RegularExpressions above public class form. Regular expression is complicated to put a pattern because of the symbol declaration. however, I already created a simple pattern that restrict the input of a user. There’s should be satisfied the input otherwise error occurred.

   1.  Example pattern ^\d{5}$ that accepts 5 numeric digits.
    Dim MyRegex As New Regex("^\d{5}$")
    Dim Input As String = TextBox2.Text
        If MyRegex.IsMatch(Input) Then
            MessageBox.Show("Correct")
        Else
            MessageBox.Show("Error")
        End If
   2.  Example pattern ^(\d{3})(-\d{4})?$ that accepts 3 numeric digits, or 3 digits-dash-4 digits.
    Dim MyRegex As New Regex("^(\d{3})(-\d{4})?$")
    Dim Input As String = TextBox2.Text
        If MyRegex.IsMatch(Input) Then
            MessageBox.Show("Correct")
        Else
            MessageBox.Show("Error")
        End If
The above code matched any digits exactly 3 times, or you can specified [2-9]  instead of \d, it’s up on how you are going to pattern. You can also create email address pattern based the above code, instead of dash(-) put At(@),Dot(.), etc. More about how to handle input data here and for Regular Expression here.

Regular Expression in VB.Net


How to use Regular Expression in VB.net? Regular Expression (Regex) is a pattern matching for string parsing for string parsing and replacement. The best example for this Regex is the pattern of email addresses, urls, etc., obviously, it provides powerful tool to avoid entering unacceptable data in our system.

Quantifiers
  
Quantifier matches several characters you need to use. The most important quantifiers are *?+, where in * matches any number of what’s before it, from zero to infinity, ? matches zero or one, and + matches one or more.


Here are some available special characters available for regex building.
.
The dot matches any single character.
\n
Matches a newline character (or CR+LF combination).
\t
Matches a tab (ASCII 9).
\d
Matches a digit [0-9].
\D
Matches a non-digit.
\w
Matches an alphanumberic character.
\W
Matches a non-alphanumberic character.
\s
Matches a whitespace character.
\S
Matches a non-whitespace character.
\
Use \ to escape special characters. For example, \. matches a dot, and \\ matches a backslash.
^
Match at the beginning of the input string.
$
Match at the end of the input string.

Character classes

You can group characters by putting them between square brackets. This way, any character in the class will match one character in the input.
[abc]
Match any of a, b, and c.
[a-z]
Match any character between a and z. (ASCII order)
[^abc]
A caret ^ at the beginning indicates "not". In this case, match anything other than a, b, or c.
[+*?.]
Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.
Here are some sample uses.
Regex
Matches
Does not match
[^ab]
cdz
ab
^[1-9][0-9]*$
Any positive integer
Zero, negative or decimal numbers
[0-9]*[,.]?[0-9]+
.111.2100,000
12.
Grouping and alternatives
It's often necessary to group things together with parentheses ( and ).
Regex
Matches
Does not match
(ab)+
abababababab
aabb
(aa|bb)+
aabbaaaabbaaaa
abab
Notice the | operator. This is the Or operator that takes any of the alternatives.
Sample code in Visual Basic.Net Regular Expression that count words and characters.
 Dim quote As String = txtdata.Text
 Dim numWords As Integer = Regex.Matches(quote, "\w+").Count
 Dim numChars As Integer = Regex.Matches(quote, ".").Count

 lblnumchar.Text = (numChars)
 lblnumofwords.Text = (numWords)
The above code must place in textchanged event or double click the specified textbox. You may also create you own pattern, here we go.

Date and time format in VB.Net



A standard date and time format string uses a single format specifies to define the text representation of a date and time value. Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string. More about standard date and time format string visit MSDN Library.

Here are the following codes:

Example 1
Dim time As DateTime = DateTime.Now
        Dim format As String = "MMM " & "," & "ddd d HH:mm yyyy"
        MessageBox.Show(time.ToString(format))
Output: May, Tue 18 16:46 2010
Example 1
Dim now As DateTime = DateTime.Now

        MessageBox.Show(now.ToString("d"))
        MessageBox.Show(now.ToString("D"))
        MessageBox.Show(now.ToString("f"))
        MessageBox.Show(now.ToString("F"))
        MessageBox.Show(now.ToString("g"))
        MessageBox.Show(now.ToString("G"))
        MessageBox.Show(now.ToString("m"))
        MessageBox.Show(now.ToString("M"))
        MessageBox.Show(now.ToString("o"))
        MessageBox.Show(now.ToString("O"))
        MessageBox.Show(now.ToString("s"))
        MessageBox.Show(now.ToString("t"))
        MessageBox.Show(now.ToString("T"))
        MessageBox.Show(now.ToString("u"))
        MessageBox.Show(now.ToString("U"))
        MessageBox.Show(now.ToString("y"))
        MessageBox.Show(now.ToString("Y"))

Output:

5/18/2010
Tuesday, May 18, 2010
Tuesday, May 18, 2010 4:47 PM
Tuesday, May 18, 2010 4:47:55 PM
5/18/2010 4:47 PM
5/18/2010 4:47:55 PM
May 18
May 18
2010-05-18T16:47:55.9620000-06:00
2010-05-18T16:47:55.9620000-06:00
2010-05-18T16:47:55
4:47 PM
4:47:55 PM
2010-05-18 16:47:55Z
Tuesday, May 18, 2010 10:47:55 PM
May, 2010
May, 2010

Example 3
Dim now As DateTime = DateTime.Now

        MessageBox.Show(now.ToLongDateString())
        MessageBox.Show(now.ToLongTimeString())
        MessageBox.Show(now.ToShortDateString())
        MessageBox.Show(now.ToShortTimeString())
        MessageBox.Show(now.ToString())
Output:

Tuesday, May 18, 2010
4:49:57 PM
5/18/2010
4:49 PM
5/18/2010 4:49:57 PM
 
Example 3
Dim now As DateTime = DateTime.Now

        ' Print out all the days.
        For index As Integer = 0 To 6
            MessageBox.Show(now.ToString("ddd"))
            now = now.AddDays(1)
        Next
Output:

Tue
Wed
Thu
Fri
Sat
Sun
Mon

Example 4
Dim now As DateTime = DateTime.Now
        For index As Integer = 0 To 6
            MessageBox.Show(now.ToString("dddd"))
            now = now.AddDays(1)
        Next
Output:

Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday

Example 5
  Dim now As DateTime = DateTime.Now
        For index As Integer = 0 To 1
            MessageBox.Show(now.ToString("tt "))
            now = now.AddHours(12)
        Next
Output:

PM
AM

Example 6
   Dim now As DateTime = DateTime.Now
        MessageBox.Show(now.ToString("yy"))
        MessageBox.Show(now.ToString("yyyy"))
Output:

10
2010

The following are examples of user-defined date and time formats for December 7, 1958, 8:50 PM, 35 seconds.

Format
Displays
M/d/yy
12/7/58
d-MMM
7-Dec
d-MMMM-yy
7-December-58
d MMMM
7 December
MMMM yy
December 58
hh:mm tt
08:50 PM
h:mm:ss t
8:50:35 P
H:mm
20:50
H:mm:ss
20:50:35
M/d/yyyy H:mm
12/7/1958 20:50
















You can use a variety of format characters on the DateTime type. For more information, visit MSDN Library.

Adding images to database in VB.Net





Adding Images that store into database in Visual Basic.Net


Save Image
Load Image









This is the line of code that save images to database.
Imports System.Drawing.Image
Imports System.IO
Public Class Form2
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load        btnimage.Enabled = False
        FirstnameTextBox.Enabled = False
        LastnameTextBox.Enabled = False
        MiddlenameTextBox.Enabled = False
        GenderTextBox.Enabled = False
        'TODO: This line of code loads data into the 'DbSaveImgDataSet.tblsaveimg' table. You can move, or remove it, as needed.
        Me.TblsaveimgTableAdapter.Fill(Me.DbSaveImgDataSet.tblsaveimg)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        If FirstnameTextBox.Text = "" Or LastnameTextBox.Text = "" Then
            MessageBox.Show("Please fill the textbox")        Else
            Me.Validate()           Me.TblsaveimgBindingSource.EndEdit()            Me.TblsaveimgTableAdapter.Insert(FirstnameTextBox.Text, LastnameTextBox.Text, MiddlenameTextBox.Text, GenderTextBox.Text, convertimage(Me.PictureBox1.Image))
Me.TblsaveimgTableAdapter.Fill(DbSaveImgDataSet.tblsaveimg)            Me.TblsaveimgTableAdapter.Update(DbSaveImgDataSet.tblsaveimg)
            MessageBox.Show("Completed")        End If
        For Each item As Control In Controls            If TypeOf item Is TextBox Then
                item.Text = String.Empty
            End If
        Next
    End Sub

    Public Function convertimage(ByVal myimage As Image) As Byte()        Dim mystream As New MemoryStream()        myimage.Save(mystream, System.Drawing.Imaging.ImageFormat.Jpeg)
        Dim mybytes(mystream.Length - 1) As Byte
        mystream.Position = 0        mystream.Read(mybytes, 0, mystream.Length)
        Return mybytes
    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimage.Click
        Me.OpenFileDialog1.FileName = Nothing
        Me.OpenFileDialog1.ShowDialog()
        If Not Me.OpenFileDialog1.FileName = Nothing Then
            Me.PictureBox1.ImageLocation = Me.OpenFileDialog1.FileName
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click        TblsaveimgBindingSource.AddNew()        FirstnameTextBox.Enabled = True
        LastnameTextBox.Enabled = True
        MiddlenameTextBox.Enabled = True
        GenderTextBox.Enabled = True
        btnimage.Enabled = True
        FirstnameTextBox.Focus()    End Sub
End Class

Note: You are going to provide or create your own database to save your data.


Validate email in VB.Net


Validate email address with Regular expression in VB.Net. However, the source code online, if I copy the code and paste it, I got an error. Absolutely, I found it.

I used Dim check As New System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)

And I imported:

Imports System.Text.RegularExpressions

Sample Screenshot
These simple lines of code determine the format of email address.

Imports System.Text.RegularExpressions
Public Class frmemail
    Private Sub btnok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnok.Click
        Dim email As String
        Dim hold As String
        email = txtemail.Text        hold = IsValidEmail(email)
        If hold = True Then
            MessageBox.Show("Correct")        Else
            MessageBox.Show("Error")        End If
    End Sub
    ''' <summary>
    ''' method for determining is the user provided a valid email address
    ''' We use regular expressions in this check, as it is a more thorough
    ''' way of checking the address provided
    ''' </summary>
    ''' <param name="email">email address to validate</param>
    ''' <returns>true is valid, false if not valid</returns>
    Public Function IsValidEmail(ByVal email As String) As Boolean
        'regular expression pattern for valid email
        'addresses, allows for the following domains:
        'com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
        Dim pattern As String = "^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\." & _        "(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$"
        'Regular expression object
        'Dim check As New Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)'I modified this code
        Dim check As New System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)        'boolean variable to return to calling method
        Dim valid As Boolean = False
        'make sure an email address was provided
        If String.IsNullOrEmpty(email) Then
            valid = False
        Else
            'use IsMatch to validate the address
            valid = check.IsMatch(email)        End If
        'return the value to the calling method
        Return valid    End Function
End Class