Category Archives: VB.NET

Area not working in MVC4 project in VB.NET

If you have had experience this problem then read ahead it is a simple fix.

 

Here are the step to reproduce this problem in Visual Studio

 

Here is what happened, I had a MVC4 project which was working fine. I created a new area called Admin.

Created a new controller and a view in the admin area. But when calling this view, it would give 404 error.

Tried few things and did some research on the net as usual.

 

Here is the simple fix which seems to work.

Go to your controller and add the namespace at the top . Just after the imports. Note that admin is the name of my area.

Change it according to your area name

 

Step 1

Imports System.Data.Entity

Namespace Areas.admin

You controller code is here

End Namespace

 

Step 2

Go to your Area and look for a file called

adminAreaRegistration.vb ( again admin is my area name, if your area is called sales then you should have a file called sales
AreaRegistration.vb. And your namespace will be Areas.sales.)

Ensure that the name space which you have in your controller  and the adminAreaRegistrarion.vb is the same

Namespace Areas.admin
Public Class adminAreaRegistration
Inherits AreaRegistration

Public Overrides ReadOnly Property AreaName() As String
Get
Return “admin”
End Get
End Property

Public Overrides Sub RegisterArea(ByVal context As System.Web.Mvc.AreaRegistrationContext)
context.MapRoute( _
“admin_default”, _
“admin/{controller}/{action}/{id}”, _
New With {.action = “Index”, .id = UrlParameter.Optional} _
)
End Sub
End Class
End Namespace

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
Debug.Print(item.CategoryID)
Debug.Print(item.VideoName)
Next

Programatically fill DataGridView using Entity Framework in VB.NET

It is quite easy to fill the DataGridView programatically in VB.NET.

There is no need to use the dataset, Data navigator and other such controls.

Here is an example/

There is a Model called Video already defined in my project and I need to display them in a datagrid view.

For the purpose of demonstrating I have kept it simple but we can use LINQ to build a complex query and then return that and display in the DataGridView.

 

 Private Sub frmVideoBrowse_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Me.DataGridView1.DataSource = GetVideos()

End Sub
Function GetVideos() As List(Of Video)
Dim db As New Entities
Dim resultlist As List(Of Video)
resultlist = db.Videos.ToList()
Return resultlist
End Function

How to use PagedList.MVC in MVC5 using VB.NET

Installed the PagedList.MVC  in your project using the NuGET

This is the ASP.NET Syntax

In your Controller

Here

At the top of the Controller add the following two imports

Imports PagedList
Imports PagedList.Mvc

 

Here is a sample ViewResult

Function NewVideos(Optional ByVal Page As Integer = 1) As ViewResult
Dim videos = rep.GetNewVideos.ToPagedList(Page, 10)  ‘ Code to get your data  use your own

ViewBag.CurrentSort = videos
Return View(videos)

End Function

 

In your View

At the top of the page add the following imports

<%@ import Namespace=”PagedList” %>
<%@ import NameSPace=”PagedList.Mvc” %>

 

Where you want the Pager to appear add the following code. Customize it according to your need.

 

<%: Html.PagedListPager(DirectCast(ViewBag.CurrentSort, IPagedList), Function(page) Url.Action(“newvideo“, New With {.page = page}), PagedListRenderOptions.OnlyShowFivePagesAtATime)%>

How to pass a variable from one winform to another in vb.net

There is often a need to pass a variable from one Winform to another.

There are two scenarios

Let us say you have two forms

1. You opened Form1 and then you want to open a new form called Form2 and you would want to carry some information from Form 1 to Form2.

The user has typed the Employee name  JOHN in the text box on the first form and then clicked on the Lookup Dept. This openes the second lookup form (Form2) where the user can select a Dept Name.

Notice that on the Form2 we have the Employee Name shown ( form1 opened  form2 and passed the value of EmployeeName)

SendVariablefromForm1ToForm2

2. You  have Form1 and Form2 already open and you want to pass a variable from Form2 to Form1

 

Once we select the Dept B on the Form 2 we click on Select and close. The second form (Form2) closes and the value of the selected department Dept B is passed back to the First form (Form1)

 

SendVariablefromForm2toForm1

 

Here is the code for the Form1

 

Public Class Form1
WithEvents fr As New Form2   ‘ Declare the new form using WithEvents
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
fr.lblEmployeeName.Text = Me.TextBox1.Text  ‘ Send the value of Textbox1 to the second Form
fr.Show()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub fr_GetDepartment() Handles fr.GetDepartment   ‘ This is the new Event which has been declared and raised from Second Form

Me.TextBox2.Text = fr.ListBox1.SelectedItem.ToString  ‘ The Listbox selected item value has been received from the second form

End Sub
End Class

Here is the code for Form2

 

 

Public Class Form2
Event GetDepartment()   ‘ You declare this Event for this Form which can be trapped from Form1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me.ListBox1
.Items.Add(“Dept A”)
.Items.Add(“Dept B”)
.Items.Add(“Dept C”)
End With
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RaiseEvent GetDepartment()   ‘ We raise the event here in Form2 which will provide you an opportunity to trap it in Form1
Me.Close()
End Sub
End Class

 

 

 

How to fill a ComboBox using a DataTable in VB.NET

A Combo box has two properties

 

1.One which displays the items in the combo box called the DISPLAY MEMBER

2. Another one which stores the underlying ID for the Item which is being Displayed.

 

eg your table may have EmployeeId and EmployeeName.

You would like to display the EmployeeName in the ComboBox and when a user selects an employee name you would like to save the EmployeeID.

Function Fillcombo(ByVal SQL As String, ByVal CBO As ComboBox, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim dt As New DataTable                  'Create a New DataTable
Dim dc As New SqlCommand              'Create a New SQLCommand
Dim da As New SqlDataAdapter         ' Create a New SQL Data Adapter
dc.CommandTimeout = 0
dc.CommandText = sql
da.SelectCommand = dc
dc.Connection = cn

da.Fill(dt)    ‘ Use the DataAdapter to fill the DataTable with the records
Try
CBO.DataSource = dt
CBO.DisplayMember = DisplayMember   ‘ This is the item which will be displayed on the combo box  eg Employee Name
CBO.ValueMember = ValueMember       ‘ This is the value which is stored eg. employeeID

Catch
MsgBox(“Unable to Fill the Combobox:” & CBO.Name & ” with values” & “:” & Err.Description)
End Try
End Function

 

 How to use the above function

Fillcombo(“Select EmployeeID,EmployeeName from Employees”, Me.EmployeeCombo, “EmployeeName”, “EmployeeID”)

How to Validate Australian Tax file number (TFN) in VB.NET

Here is a code snippet to help you validate the Australian Tax File Numbers also known as TFN.

The TFNs are 9  character long Numeric values

Here is a Sample TFN  123456782 which you can use to do your testing.

 

 

Function Validate_TFN(ByVal value As String) As Boolean

        ‘ best-answer.net

        Dim bok As Boolean = False
        ‘ the following algorithm is used to calculate the validity of TFN

        ‘ 9 characters
        Dim myTFN As Char()
        ‘
        Dim checksum As Double

        Dim count As Integer
        myTFN = value.ToCharArray()
  
        Dim i As Integer
        For i = 0 To 8
            Select Case i

                Case 0
                    checksum += myTFN(0).ToString * 1
                Case 1
                    checksum += myTFN(1).ToString * 4
                Case 2
                    checksum += myTFN(2).ToString * 3
                Case 3
                    checksum += myTFN(3).ToString * 7
                Case 4
                    checksum += myTFN(4).ToString * 5
                Case 5
                    checksum += myTFN(5).ToString * 8
                Case 6
                    checksum += myTFN(6).ToString * 6
                Case 7
                    checksum += myTFN(7).ToString * 9
                Case 8
                    checksum += myTFN(8).ToString * 10

            End Select

        Next
        checksum = checksum / 11

        bok = (Math.Floor(checksum) = Math.Ceiling(checksum))
        Return bok
    End Function

How to use ErrorProvider in VB.NET

Error Provider is a cool control which provides visual indications of any errors which you catch.

eg. If you have a text box which is supposed to captured the names of people and if someone leaves it blank you can use Error Provider to provide a visual indication of the error.

 

 

Here is a video  to explain the use of the error provider.

Here is a quick sample of how to use the error provider in vb.net

 

If Len(me.txtName.Text) > 50 Then
                Me.ErrorProvider1.SetError(me.txtName, “First Name can not be more than 50 chars”)
Else
                Me.ErrorProvider1.SetError(me.txtName, “”)
              
End If