Category Archives: WPF

How to download a file in MVC4 using VB.NET

How to allow File Downloads in MVC4 using VB.NET

We are using an ActionResult instead of FileResult.

Function download(id as Integer) As ActionResult

The reason is that if use the FileResult and your file does not exist then it will show a blank page, instead of this

we are using an ActionResult which is more versatile.
We can return the actual FileResult if the file exists
and in case of an error we can return a View (if we used a FileResult

Function download(id as Integer) As ActionResult

‘ In this example we are using the id to pick up the actual file from a model

Dim SoundFile as SoundFile = db.SoundFiles.Find(id)

Dim path As String = Server.MapPath(“~/myLocation/” & SoundFile.MP3File)

‘get file object as FileInfo
Dim fileinfo As System.IO.FileInfo = New System.IO.FileInfo(path)

‘– if the file exists on the server

If fileinfo.Exists Then
rep.IncrementDownloadCount(id) ‘This is my routine to count the downloads, you will not need it
Return File(path, “application/octet-stream”, fileinfo.Name)
Return View(“Error”)
End If

End Function

How to generate Random Integers in VB.NET

Here is a simple way to generate Random Integers in VB.NET


Dim iRnd As Integer = CInt(Math.Ceiling(Rnd() * n))


Where n is the max number


eg.    Dim iRnd As Integer = CInt(Math.Ceiling(Rnd() * 10))


will generate random numbers between 1 and 10




How to get ListBox Selected Text in VB.NET Winforms

Here is a simple snippet to get the selected text of the list box in

Make use of the SelectedIndexChanged Event of the listbox and add the following code in it



Private Sub lstBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstBox.SelectedIndexChanged
Me.lblCategory.Text = Me.lstBox.GetItemText(Me.lstBox.SelectedItem)
End Sub

How to loop through records in LINQ using VB.NET in Entity Framework

Here is a simple code snippet to loop through the records in VB.NET using LINQ


The following code example takes the records from an Entity Framework Model named as Video and then allows to loop through each record.



Dim List As List(Of Video)

List = (From video In db.Videos Order By video.ID Descending).ToList
For Each item In List

How to conditionally change the BackColor of a Row in DataGridView in VB.NET

Here is a working code for changing the DataGridView row colors based on condition.

In this code I am checking if the Cell called “Date Closed” is present or not, so if a row item has a closed date present then I would like to show that row in Red Color.

It is easy to do, just put your conditions in the If End If block shown below according to your needs


Private Sub dgr_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgr.CellFormatting

        If e.RowIndex >= 0 Then
            If IsDate(dgr.Rows(e.RowIndex).Cells(“Date Closed”).Value) Then

                e.CellStyle.ForeColor = Color.Red
            End If

        End If

    End Sub


Here is the snapshot of the above code in action.


Change the DataGridView Rowcolor conditionally

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 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 execute a SQL Server Procedure in VB.NET

How to execute a Backend Procedure in SQL Server using VB.NET

Here is a function which allows you to execute a SQL Server Procedure in VB.NET

Function ExecuteProcedure_DeleteRecord() as boolean

Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim sql As String

sql = "cs_Post_Delete"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@SectionID", "200") ' string then enclose it in the double quotes
cmd.Parameters.AddWithValue("@SettingsID", 1000) ' numeric value then you can put it without any quotes
cmd.Parameters.AddWithValue("@PostID", Me.TextBox1.Text) ' Here we are picking a value from a textbox
cmd.Parameters.AddWithValue("@ResetStatistics", 1)
cmd.Parameters.AddWithValue("@DeletedBy", 2109)
cmd.Parameters.AddWithValue("@Reason", "Deleted due to SPAM")
cmd.CommandText = sql
cmd.Connection = cn

'Call Open database - connect to the database
OpenConnection(cn) ' I use a seperate function to open a new connection

MsgBox("Unable to Delete the record:," & Err.Description)
CloseConnection(cn) ' I use a seperate function to close an existing connection
MsgBox("Record Deleted")
End Try

End Sub