Category Archives: VB.NET

How to create a Datatable programatically in VB.NET

Dim dt as new DataTable   
        ' Add the columns which you need in your datatable
        dt.Columns.Add("SNo", GetType(Integer))  '1
        dt.Columns.Add("Details", GetType(String))  '2
        dt.Columns.Add("Qty", GetType(String))  '3
        dt.Columns.Add("UnitRate", GetType(Double)) '4
        dt.Columns.Add("ApplyTax", GetType(Boolean))  '5
        dt.Columns.Add("ExTaxTotal", GetType(Double))  '6
        dt.Columns.Add("Tax", GetType(Double))  '7
        dt.Columns.Add("InclTaxTotal", GetType(Double)) '8
       
        ' Create a new row for your table
        Dim drow = dt.NewRow()

        ' Now add the items in your newly created row
        drow.Item(0) = 1
        drow.Item(1) = "My Details go here"
      
        drow.Item(2) = 1
        drow.Item(3) = 234
        drow.Item(4) = 1
        drow.Item(5) = drow.Item(2) * drow.Item(3)   ' You can also calculate the values
        drow.Item(6) = drow.Item(2) * 0.1
        drow.Item(7) = drow.Item(5) * drow.Item(6)


        ' Now add this row to the table
        dt.Rows.Add(drow)

        ' If you want you can display this  data in a datagrid  
        Me.DataGridView1.DataSource = dt

How to get the list of installed printers in vb.net

To get the list of installed printers on your computer use the following code which will populate a Combo box with the list of installed printers.

 

Private Sub PopulateInstalledPrintersCombo()
        ' Add list of installed printers found to the combo box. 
        ' The pkInstalledPrinters string will be used to provide the display string. 
        Dim i As Integer
        Dim pkInstalledPrinters As String

        For i = 0 To Printing.PrinterSettings.InstalledPrinters.Count - 1
            pkInstalledPrinters = Printing.PrinterSettings.InstalledPrinters.Item(i)
            comboInstalledPrinters.Items.Add(pkInstalledPrinters)

        Next
    End Sub

Learn how to printer address labels on Dymo Label Printer in VB.NET

Print address label on Dymo using VB.NET – Address label printing on Dymo using VB.NET

If you have the need to print the address labels then this script will get you started, this is a very simple script which will get

you started. You can visit Dymo website site and checkup the SDK for complex scenarios.

 

Assumption

I assume that you have already attached a Dymo Label printer to your computer.

I am using Dymo LabelWriter 400

 

Step 1

You would need to add references to your your project

Add reference to your project

 

 

Step 2

On top of your form add the following imports.

Imports DYMO.Common
Imports DYMOPrintingSupportLib
Imports DYMO.DLS.Runtime

 

Step 3

Add a button on your form  and call it btnPrintLabel

Step 4

Add the following lines of code to the click event of your button

 Private Sub btnPrintLabel_Click(sender As Object, e As EventArgs) Handles btnPrintLabel.Click
 Dim Label As DYMO.Label.Framework.ILabel
 Label = DYMO.Label.Framework.Framework.Open("C:\Users\User\Documents\DYMO Label\Labels\Holroyd Council.label")
 Label.SetAddressText(0, "First address Line" & vbCrLf & "Second Line" & vbCrLf & "Third Line")

 Label.Print("DYMO LabelWriter 400")  ' This is the name of my printer, replace it with your printer name
 End Sub

How to find out the names of installed printers in 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

 

Generate RSS Feed in MVC4 using VB.NET

Here is a simple function to generate the RSS feeds.
This article assumes that you are using MVC4 project with Entity Framework. Just iterate through

the relevant table to pick your data which you want to show in the RSS feed.

Remember to add the following import statements at the top of your controller
Imports System.Xml
Imports System.IO

In your controller create a function as shown below. There is no need to create a corresponding View for it

as the function will write to the RESPONSE and the XML output will be provided by the XMLTextWriter.

Function RSSNewArticles() As Action

Response.Clear()
Response.ContentType = “text/xml”
Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
objX.WriteStartDocument()
objX.WriteStartElement(“rss”)
objX.WriteAttributeString(“version”, “2.0”)
objX.WriteStartElement(“channel”)
objX.WriteElementString(“title”, “MyWebsite.com RSS Feed“)
objX.WriteElementString(“link”, “http://mywebsite.com“)
objX.WriteElementString(“description”, “My website New Articles Feed“)
‘ objX.WriteElementString(“copyright”, “(c) 2014, best-answer.net“)
objX.WriteElementString(“ttl”, “10”)

‘Populate record for the RSS feed

For Each item In db.MyDataTable
objX.WriteStartElement(“item”)
objX.WriteElementString(“title”, item.CatName)
objX.WriteElementString(“link”, “http://mywebsite/” & item.RecordID & “/” & item.TitleName)
objX.WriteElementString(“pubDate”, Now)
objX.WriteEndElement()
Next

objX.WriteEndElement()
objX.WriteEndElement()
objX.WriteEndDocument()
objX.Flush()
objX.Close()
Response.End()
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