Tag Archives: VB.NET

Using Grid.MVC in MVC4 using VB.NET

There are numerous example for C3 but I had to spend quite some time to adapt it to my project using VB.NET

 

Hope it can be of help to you.

I assume that you have

already added the GridMVC package from NUGET.

Here are step by step guide

Controller

No change needed , see a sample below,

Function Index() As ActionResult
Return View(db.Categories.ToList())
End Function

View

Add the following import at the top of your view

@imports  GridMVC.html

 

You would need to reference the following also

 

Add the stylesheets (check the location after you install the GridMVC package)

<link href=”~/Content/Gridmvc.css” rel=”stylesheet” />
    <link href=”~/Content/gridmvc.datepicker.min.css” rel=”stylesheet” />
For your paging support

Install the PagedList package also

Once you have installed this package then add the following reference to your view, this will help you format your paging buttons

properly.

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

Add the following code for your Grid to appear – In the following examples my Model has three fields – CatId, CatName

and ParentCatId. Make changes to suit your needs.

@Html.Grid(Model).Columns(Function(columns)
                                   
                              columns.Add(Function(o) o.CatID).Titled(“Cat #“).SetWidth(40)
                                 
                              columns.Add(Function(o) o.CatName).Titled(“Category“).SetWidth(100)
                                  
                              columns.Add(Function(o) o.ParentCatID).Titled(“Parent Cat #“).SetWidth(40)
                          
                          End Function
).WithPaging(10).Sortable(True)

 

 

 

A potentially dangerous Request.Form value was detected from the client – error in MVC4 in vb.net

In your Create Actions in a Controller in MVC4, if you try to save text with html tags then you get this annoying error.

A potentially dangerous Request.Form value was detected from the client

Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874.

This is a great protection if you do not want your client to save html text.

Here is how to get rid of this error

In the following example we have a create action which saves a new record. MVC4 controller will have two functions.

The first function is for GET ( this is the one which will render the page to save the new record

 

The second function is for POST. This function is responsible to receive the model
which has been populated by the data which the user has filled in on the form. We have to add the following text

<ValidateInput(False)>

 

for C# add

[ValidateInput(false)]

 

 

 

 

‘ GET: /admin/ManageAds/Create

Function Create() As ActionResult
Return View()
End Function

 

 

‘ POST: /admin/ManageAds/Create
<HttpPost()> _
<ValidateAntiForgeryToken()> _
<ValidateInput(False)>
Function Create(ByVal ad As Ad) As ActionResult
If ModelState.IsValid Then
db.Ads.Add(ad)
db.SaveChanges()
Return RedirectToAction(“Index”)
End If

Return View(ad)
End Function

 

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)
Else
Return View(“Error”)
End If

End Function

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

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 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

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
        listView.Clear()
        For ii = 0 To iColCount – 1
            listView.Columns.Add(dt.Columns(ii).ColumnName, 250, HorizontalAlignment.Left)
          
        Next
   
        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
                Application.DoEvents()
                lst.SubItems.Add(SNZ(dt.Rows(i).Item(x)))
             
            Next

               Application.DoEvents()
           ‘    If you want to display the progress then you can do it here
           ‘ myStatusLabel.text = “Displaying Record ” & i + 1 & “/” & iRowCount
            listView.Items.Add(lst)
            lst = Nothing
        Next
    
    End Sub

Implement PagedList in VB.NET MVC3 or MVC4

How to use Paging using the PagedList

Once you have installed the PagedList package from NUGET

 

Controller

 

Add the following two imports at the top of the header

Imports PagedList
Imports PagedList.Mvc

 

 

Your Linq or SQL query should be sorted

eg.

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)

 

 

View

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

“ViewBag.search – 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 = ViewBag.search}), PagedListRenderOptions.OnlyShowFivePagesAtATime)