Category Archives: VB.NET

How to fill up a ListView from database in VB.NET using a DataTable

You can easily use the following code to fill up your listview control from the data in a datatable using VB.NET


Supply the name of your listview and the datatable to this procedure and it will fill it up your list view.

If you wish to display the ongoing process then you can do that as well. Just create a label and then uncomment the following text in the procedure. Create a label and call it myStatusLabel.

‘ myStatusLabel.text = “Displaying Record ” & i + 1 & “/” & iRowCount



Sub FillListViewByTable(ByVal listView As ListView, ByVal dt As DataTable)
        Dim ii As Integer
        Dim iColCount As Integer = dt.Columns.Count
        Dim iRowCount As Integer = dt.Rows.Count
        For ii = 0 To iColCount – 1
            listView.Columns.Add(dt.Columns(ii).ColumnName, 250, HorizontalAlignment.Left)
        Dim i As Integer
        Dim x As Integer
        For i = 0 To iRowCount – 1  ‘ for each row in the table
            Dim lst As New ListViewItem
            lst.Text = dt.Rows(i).Item(0)
            lst.UseItemStyleForSubItems = True
            For x = 1 To iColCount – 1 ‘ for each column in the row of the table

           ‘    If you want to display the progress then you can do it here
           ‘ myStatusLabel.text = “Displaying Record ” & i + 1 & “/” & iRowCount
            lst = Nothing
    End Sub

How to duplicate a winform in Visual Studio easily

You start with a new project and you have created a winform with graphics and the functionality which you want to use in all your other forms in the same project.

One would think that it is easily done as we can simply copy and paste the existing form and rename it and then suddenly all will be well.

That is not the case when you Control C and Control V to copy the form. You will try to rename it but you might gets lots of errors. I have struggled with this may times.

I have discovered a fool proof way which works well.

There is an Export Functionality in Visual Studio which is handy. This functionality allows you to create a template and resuse the template form in your project .

Step 1

Go to File> Export Template in Visual Studio

Step 1
Step 1


Step 2

Step 2
Step 2

Select ITEM Template, You can also choose Project Template ( which will appear only in  your existing project).

where as ITEM template would be universally available for all new  or existing projects.

Step 3


Select the form which you want to clone

Step 3
Step 3


Step 4


You might need to select the references which you want to be included, select the ones which you think will need. You can always add them later using the code in your project  using the USING command  in C# or IMPORTS command in VB.NET after you have cloned a form.

Step 4
Step 4


Step 5


Provide a new name and some useful description to your new template.

Step 5
Step 5

Step 6


when you click on Finish in Step 5 the new template will be created in the Windows Folder as you can see below.

Step 6
Step 6


Step 7


When you click on ADD NEW ITEM in your Visual Studio project you should be able to see you newly created Template. You can use this template whenever there is a need . I found this approach simpler and safer than merely copying and pasting an existing form.

Step 7
Step 7

How to restrict free Data Entry in ComboBox in Visual Studio

When you create a Combo Box in Visual Studio  , the default behaviour is that it will show the list and it will also allow the data entry. So a user can type something in instead of selecting the options listed in the Combo Box. This can cause issues as you might want the user to only select the valid options which are listed in your combo box.


Here is a simple way to achieve this behavior. Highlight the Combo Box on your form. The properties window will be show.

Change the Drop Down Style to  DropDownList as shown below.

Your combo box will not allow the users to type in any free text. they will have to select the options listed in your combo box.



How to make all labels backcolor as transparent in VB.NET in Visual Studio

If you have a winform with a background image then you would notice that the label background colour will not match the background so it will look like this.



NB: You can also use the properties to make the label Transparent. The Transparent option is available in the Web colors.


Step 1

But you can easily do it in the code by this code

tlblName.BackColor= Color.Transparent

Step 2

If you have a number of labels on the form then you can loop through each and make the background  colour transparent.








Here is a code to make the background of the label as transparent.

For Each formLabel As Label In Me.Controls.OfType(Of Label)()
            formLabel.BackColor = Color.Transparent
        Next formLabel








How to Validate an Email Address in VB.NET using REGEX

If you have a need to validate a user input or string to ensure that only a valid email is entered , then you can use Regular Expressions or REGEX  to handle that easily.

REGEX expressions appear to be quite complicated but once you have a valid syntax then it is simply a matter of using the proper syntax of REGEX in the following function and you should also be able to use the same function block to handle other types of inputs as well. eg. Numeric


The following function will validate your input against a valid email address.

Step 1

At the top of your module or form add the following line of code

Imports System.Text.RegularExpressions

Step 2
Add the following function in your form

Function Validate_Email(ByVal value As String) As Boolean
Dim bok As Boolean = False
Dim s As String
s = LCase(value)

Dim myMatch As Match = System.Text.RegularExpressions.Regex.Match(s, “^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$”)

If myMatch.Success Then
bok = True

Return bok
bok = False
Return bok
End If
End Function

Step 3

How to use the function

Dim bok as boolean

bok = Validate_Email( YourInputTextHere)

If the user input is a valid email then bok will be true else false.

How to fill a DataGridView using Entity Model in VB.NET

Here is a quick way of filling up and displaying the records from a table in a DataGridView

This post assumes that you already have created a EntityModel in your project

My Entity Model is called SuperHREntities and I have a table called Employees in it

The trick is to you use the .ToArray() after your table name in the following example to display the records.  If you simply try to use db.Employees then the records will not be displayed.


Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim db As New SuperHREntities
DataGridView1.DataSource = db.Employees.ToArray()

End Sub


 Click on the Image to see it in full screen.

How to fill DataGridViewUsing Entity Model






Implement PagedList in VB.NET MVC3 or MVC4

How to use Paging using the PagedList

Once you have installed the PagedList package from NUGET




Add the following two imports at the top of the header

Imports PagedList
Imports PagedList.Mvc



Your Linq or SQL query should be sorted


Dim v = (From vid In db.qry_Videos Where vid.CatID = CatID Order By vid.OrderByID Select vid)

ViewBag.CurrentSort = v   ‘ This is most important you need to tell the view what your current sort order is

Return View(v)




In your view add the following imports at the top of the view

@imports PagedList
@imports PagedList.Mvc


Add the style sheet in your view as well. This will help you render your pager properly

<link href=”~/Content/PagedList.css” rel=”stylesheet” />


Wherever you want your pager to appear use the following

index” is the name of your view, if your view is named different then change it to your view

page”  – this is the variable which stores the current page number

“ – this is the ViewBag which you used in your controller

OnlyShowFivePagesAtATime  – this tells the pager how many buttons will be shown at one time ( this option shows

@Html.PagedListPager(DirectCast(ViewBag.CurrentSort, IPagedList), Function(page) Url.Action(“index“, New With {.page = page, .criteria =}), PagedListRenderOptions.OnlyShowFivePagesAtATime)

How to Decode and Encode MIME data

This function will decode the mime data contained in a string into a BYTE and then it can be saved onto your desktop using the FileStream.

Dim byteData As Byte()
byteData = FromBase64(strMimeData)
Dim oFileStream As System.IO.FileStream
oFileStream = New System.IO.FileStream(“c:\temp\” & Me.txtAttachFileName.Text, System.IO.FileMode.Create)
oFileStream.Write(byteData, 0, byteData.Length)

This function will encode the data contained in a BYTE into MIME data which will be returned as a string

Public Function EncodeToBase64(ByVal data() As Byte) As String
If data Is Nothing Then Throw New ArgumentNullException(“data”)
Return Convert.ToBase64String(data)
End Function

This function will decode the MIME data contained in a string  and the binary data will be returned as a BYTE

Public Function  DecodeFromBase64(ByVal base64 As String) As Byte()
If base64 Is Nothing Then Throw New ArgumentNullException(“base64″)
Return Convert.FromBase64String(base64)
End Function

How to use Nested MaserPages in VB.Net websites

Well here is a situation.

I create 3 templates and each one of them will have a MasterPage. Eg. TemplateMaster1, TemplateMaster2 and TemplateMaster3

Then I create another MasterPage called SiteMasterPage

and in SiteMaster I call one of the three templates ( eg. TemplateMaster1)

Then I create a default.aspx page which will refer to the SiteMasterPage

Now the <asp:ContentPlaceHolder> tags which are in TemplateMaster1 can not be directly used in my default.aspx page

In order to use them here is a work around

Whereever you want to put the custom content.

Create a  <asp:Content> tag in  your SiteMasterPage first and then within it create a <asp:ContentPlaceHolder> tag

Here is an example.

<asp:Content ID=”Main”  ContentPlaceHolderID=”TemplateMain” runat=”server”>
<asp:ContentPlaceHolder ID=”MasterMain” runat=”server”>



Then in your default.aspx page you can place the MasterMain

<asp:Content Id=”Main” ContentPlaceHolderID =MasterMain runat=”server”>

<h1>Welcome to this content  which is using nested masterpages</h1>


Select and edit a record in GridView in

If you want to select a record in a Gridview in VB.Net and then edit that record in a separate page, then you can use the following code to give you an idea.

I assume that you alredy know how to add a gridview and populate it using

You would need to add a hyperlink field in the gridview columns as shown belo

The headertext will show what will appear in the header row
datatextfield will be name of your datafield which is the primary key for the data
datanavigateurlformatstring  – this field will construct the name of your page which the system will navigate to if someone clicks on the edit button
datanavigateurlfields  is again the primary key eg. My primary key was “NewsId”
DataTextFormatString  tells what will be displayed on the data gridl eg. I want to show a hyperlink called “Edit”

so whenever someone clicks on the edit button the system will take you to the “EditNews.aspx?q=1 where 1 will be the NewsID

<asp:hyperlinkfield headertext=”Edit” datatextfield=”NewsID” datanavigateurlformatstring=”EditNews.aspx?q={0}” datanavigateurlfields=”NewsID” DataTextFormatString=”Edit” Text=”Edit” />

Here is the complete code which shows where the hyperlink code will sit

<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True”
AllowSorting=”True” AutoGenerateColumns=”False” DataKeyNames=”NewsID”
DataSourceID=”SqlDataNews” Width=”617px”>

<asp:BoundField DataField=”NewsID” HeaderText=”NewsID” InsertVisible=”False”
ReadOnly=”True” SortExpression=”NewsID” />

<asp:BoundField DataField=”NewsDate” HeaderText=”NewsDate”
SortExpression=”NewsDate” />
<asp:BoundField DataField=”NewsStartDate” HeaderText=”NewsStartDate”
SortExpression=”NewsStartDate” />
<asp:BoundField DataField=”NewsEndDate” HeaderText=”NewsEndDate”
SortExpression=”NewsEndDate” />
<asp:BoundField DataField=”NewsShortDescripton”
HeaderText=”NewsShortDescripton” SortExpression=”NewsShortDescripton” />

<asp:hyperlinkfield headertext=”Edit”

datanavigateurlfields=”NewsID” DataTextFormatString=”Edit” Text=”Edit” />