Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Visual Basic.NET





Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,

How do I get the current Windows Region Format, e.g "French (France)" ?

What does it mean to be "Always On"?
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

I added references from http://vb.net-informations.com/files/create-pdf.htm to my vb.net program.  I have no problem creating a PDF document, but I'm trying to figure out how to change the orientation to landscape.

I tried this...
Dim pdfPage As PdfPage = pdf.AddPage.Orientation.Landscape

Open in new window

and this...

Open in new window

But neither work.  I get the options of Orientation and Landscape from auto-fill, so I know it must be possible, but I get an error in the error list saying that PageOrientation cannot be converted to pdfPage.  How do I set the orientation?
Hi Experts,

I am generating some labels as shown in Label1.png. My design is in Labeldesign.png.  My client needs the output in two columns as shown in Label_Desired.png. Please suggest is there any way to do it?

Thanks in advance.
So I added the references here...
For creating a PDF document in vb.net.  This works fine, but in my code, I don't know how to start a new line.  I tried using Evironment.NewLine, but it doesn't advance beyond the first line of text.  I'm sure the issue is that I can't keep using "TopLeft", but I can't figure out how to write multiple lines to the page.  Here's my code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pdf As PdfDocument = New PdfDocument
        pdf.Info.Title = "Renewal Report"
        Dim pdfPage As PdfPage = pdf.AddPage
        Dim graph As XGraphics = XGraphics.FromPdfPage(pdfPage)
        Dim font As XFont = New XFont("Consolas", 20, XFontStyle.Regular)
        '// Writing first line
        graph.DrawString("First Line of Document", font, XBrushes.Black,
        New XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft)
        '// Trying to add new line
        graph.DrawString(Environment.NewLine, font, XBrushes.Black,
        New XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft)
        '// Trying to write second line
        graph.DrawString("Second Line of Document", font, XBrushes.Black,
        New XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft)
        Dim pdfFilename As String = "firstpage.pdf"

Open in new window

Troubleshooting a piece of code.
            Dim web As Net.WebClient = New Net.WebClient()
            Dim html As String = web.DownloadString("https://www.google.com/finance/converter?a=1&from=EUR&to=USD")
            Dim m1 As Match = Regex.Match(html, "<span class=bld>\s*(.+?)\s*</span>", RegexOptions.Singleline)
            Dim currency As String = m1.Groups(1).Value.Replace("USD", "")


Open in new window

currency is blank.  

My question is what does "<span class=bld>\s*(.+?)\s*</span>", RegexOptions.Singleline" do?

How do I prevent users from resizing a Form by dragging its border using VB.NET?

Kind regards,

I have an aspx page that runs a stored proc. The stored proc returns a value ( a record ID) after performing a few insert statements.  I want to get that return value with vb code.  My current code (see * below) gets an error message: "Input string was not in a correct format."  I can't find the right code to get the return value.  What is the flaw(s) in my code?

Thanks for looking.

The stored proc:
CREATE PROCEDURE [dbo].[CreateEval]
	    @EmployeeNumber int
	  , @EmpLastName varchar(30)
	  , @EmpFirstName varchar(30)
	  , @EmpDepartmentID int
	  , @EmpJobTitleID int
	  , @SupervisorID int
	  , @SupLastName varchar(30)
	  , @SupFirstName varchar(30)
	  , @SupervisorDeptID int
	  , @SupervisorTitleID int
	  , @EvalID int = NULL OUTPUT

	/*some inserting happens here		

	/*some inserting happens here		

	   , SupervisorID
	   , EvalDate)
	VALUES (@EmployeeNumber
		  , @SupervisorID
		  , GETDATE())
	INSERT INTO EvalScoring

Open in new window

Here is the sql data source:
<asp:SqlDataSource ID="dsCreateEval" runat="server" ConnectionString="<%$ ConnectionStrings:EmpEval_TestConnectionString %>" SelectCommand="CreateEval" SelectCommandType="StoredProcedure"

Open in new window

I want to use the following C# code in a VB program.  How would I convert this?  The first line seems to just be a matter or removing the semicolon, but I can't test it since I am unable to figure out the second line.
textbox1.Select( textbox1.GetFirstCharIndexFromLine( 0 ), textbox1.GetFirstCharIndexFromLine( 1 ) - textbox1.GetFirstCharIndexFromLine( 0 ) );
textbox1.SelectionFont = new System.Drawing.Font( "Tahoma", 10, FontStyle.Bold );

Open in new window

How can I Draw line from datagridview1 cell to another datagridview2 cell.
Just want to show a connection.
I am using vb.net desktop.

What is the best way to take a string (let's say 99900) and string it so it equals 999.00 ?  format for some reason I am struggling with..  I think I am overthinking it but looking for other ideas.


I have also tried variants to string.format() seems to not add the decimal.  

Thanks in advance!
Free Tool: Subnet Calculator
LVL 10
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.


I have a service that used a FileSystemWatcher to monitor a directory waiting for XML files to be posted from on-site scanners and then it is to process them appropriately. The files are generated from the scanners via a PHP script to post the files into the directory being watched.

There is an issue in this application that occasionally it posts a zero-byte file that I have to detect and then delete as the file is useless. I have coded this, but it has exposed another issue that I now need to address.

Sometimes the FileSystemWatcher detects and attempts to grab the file before the post from the scanner is complete. I have added a loop to wait on the service being able to open the file with exclusive access which I thought would mean that the post was complete (assuming the file would remain locked until it was fully written). However, this occasionally appears not to be the case. On the odd occasion my loop appears to be getting exclusive access to the file (about 1% of the time) before it should (in my mind), and is detecting the file as zero-byte as the write has not completed. It then proceeds to try to delete the file, which fails as the writing process seems to again have taken out a lock on the file.

My question is, what is the best way to wait on exclusive access to a file and to be 100% sure that the writing process has finished with the file??

A snippet from my code is below (detectedFilename comes in as a parameter):


Open in new window

I have the following code, which I haven't tested thoroughly yet, but so far it seems to work well.  I'm wondering if the Try...Catch statement that I have is sufficient for error handling?

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim strArrayDate As String          '// Date of entries already in the file
        Dim strNewItemDate As String = expirationDate.Value.ToShortDateString '// Date of item being added
        Dim boolInsertionPoint As Boolean = False '// Determine if location for new item was found
        Dim delim As String = Chr(149)      '// Delimiter character
        Dim i As Integer = 0                '// line counter
        '// Backup file
            My.Computer.FileSystem.CopyFile("\\server\folder\Renewals\renewals.db", "\\server\folder\Renewals\renewals" + (Date.Now.ToShortDateString).Replace("/", "-") + ".bkp", overwrite:=True)
            '// Input file into array
            Dim lines() As String = IO.File.ReadAllLines("\\server\folder\Renewals\renewals.db")

            If strComment.Text = "Enter comments here" Then strComment.Text = "No comments added"

            '// Add each item back to the file, inserting new item in proper place
            For Each line As String In lines
                strArrayDate = lines(i).Split(Chr(149))(0)      '// Get date of entry being examined
                '// Find where new item should be inserted
                If CDate(strNewItemDate) < 

Open in new window

Hi I have used telerik to convert code but getting error, please help

this is the c# version:
System.Xml.XmlElement[] headers = doc.DocumentElement.ChildNodes.Cast<XmlElement>().ToArray<XmlElement>();

Open in new window

this is the vb converted version:
Dim headers As System.Xml.XmlElement() = doc.DocumentElement.ChildNodes.Cast(Of XmlElement)().ToArray(Of XmlElement)()

Open in new window

the error message is

Error      109      Extension method 'Public Function ToArray() As TSource()' defined in 'System.Linq.Enumerable' is not generic (or has no free type parameters) and so cannot have type arguments.

I have the: Imports System.Linq
I am using vb.net trying to send an email,   the following is my code

            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential("username@gmail.com", "myPass")
            Smtp_Server.Port = 587
            Smtp_Server.EnableSsl = True
            Smtp_Server.Host = "smtp.gmail.com"            

            e_mail = New MailMessage()
            e_mail.From = New MailAddress(Txt_FromEmail.Text)
            e_mail.Subject = "Email Sending For test"
            e_mail.IsBodyHtml = False
            e_mail.Body = Txt_Message.Text
            MsgBox("Mail Sent")

        Catch error_t As Exception
            TextBox1.Text = error_t.ToString
        End Try

and I am getting the following error

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String …

I'm trying to change multiple  panel back color depends on data from database,
the data comes from list called mylist  it have a strings with true and false,
so i need to change the back color of panels depends on that data , so if mylist(1) = true i want the back color is green:
this is what i tried  :

Dim p As List(Of Panel) = Me.Controls.OfType(Of Panel).ToList
        For i As Integer = 1 To duration
            If myList(i) = True Then
                p(i).BackColor = Color.SpringGreen
            End If

Open in new window

but its not working.
I have code  which replaces the merge field.I need to replace with backspace.How can i achieve this .
Any suggestions are appreciated.
                       ReplaceWith:=Str_Date, Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll, MatchCase:=True)

Open in new window

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;
int main()
    int pictureLength, pictureWidth, pictureSquareInchSize, picturePerimiter, numberOfStars;
    char frameType;
    string frameColour;
    float totalPrice;
    //values below represent cost per inch
    const float FRAME_COLOURING_PRICE = 0.10;
    const float REGULAR_FRAME_PRICE = 0.15;
    const float FANCY_FRAME_PRICE = 0.25;
    //values below represent cost per square inch
    const float CARDBOARD_PRICE = 0.02;
    const float GLASS_PRICE = 0.07;
    const float STARS_PRICE = 0.35;
    cout << "Please enter the length & width of the picture: ";
    cin >> pictureLength >> pictureWidth;
    pictureSquareInchSize = pictureLength * pictureWidth;
    picturePerimiter = (pictureLength * 2) + (pictureWidth * 2);
    cout << "Please select your frame type (r for regular & f for fancy): ";
    cin >> frameType;
    // Calculate cost of the frame type
    switch (frameType) {
        case 'r':
        case 'R':
            totalPrice = picturePerimiter * REGULAR_FRAME_PRICE;
        case 'f':
        case 'F':
            totalPrice = picturePerimiter * FANCY_FRAME_PRICE;
            cout << "You entered an invalid fram type" << endl;
            return 1;
    cout << "Please enter which colour frame you would like (Note: white is …
I have placed some sql statements in an XML document to load into my program.
    <QueryName>Exact Production Orders </QueryName>
          Select * from ppordfil_sql

Simple queries load just fine but when I add a Where ColumnA < 0 I get a parse error on the < sign.

I load this XML from a file.

 xmlDoc.Load(My.Application.Info.DirectoryPath & "\sql.xml")

The program will load all nodes except this one with the < in the query.
I get a "Name" cannot begin with a "<" character, hexadecimal value XXXX Line xxx position xxx.

What would a good work around be?  (Besides not having queries with < in them.)

The queries are SQL Server type queries.

Hi Guys, any idea why this While Wend Loop is only populating Cells (i,44) and not Cells (i,88) in Excel. The If Statements are exactly the same.

Sub Newmacro()


Dim i As Long

i = 1

While Cells(i, 1).Value <> ""

If Cells(i, 4).Value = "MM_BNK_LN" And Cells(i, 21).Value = "EUR EURIBOR 3M" And Cells(i, 18).Value = "GB-RELATIONSHIP LOAN" Then
Cells(i, 44).Value = "-0.332"
i = i + 1
ElseIf Cells(i, 4).Value = "MM_BNK_LN" And Cells(i, 21).Value = "EUR EURIBOR 3M" And Cells(i, 18).Value = "GB-RELATIONSHIP LOAN" Then
Cells(i, 81).Value = "-0.332"

i = i + 1


i = i + 1

End If
Concerto's Cloud Advisory Services
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Object reference not set to an instance of an object error
I have a SQL table named tblBuildQueriesSQL. This table has 7 fields: See attached file.

UniqueID - Primary Key

How can I execute this tblBuildQueriesSQL table using VB.net?

Please help.

Thank you.
I am trying to automate an email inside my vb.net program. I am using the following line of code below.
I get to the SMTP.Send(Mail) and get an error. (See attached image). It will never show up in my mailbox.

  Dim Mail As New Net.Mail.MailMessage
        Mail.Subject = "Notification Email."
        Mail.From = New MailAddress("*******@*******corporation.com")
        Mail.Body = "This is a notice that a report was created."

        Dim SMTP As New SmtpClient("smtp.gmail.com")
        SMTP.EnableSsl = True
        SMTP.Credentials = New System.Net.NetworkCredential("******@gmail.com ", "******")
        SMTP.Port = "587"

Open in new window

Hi Experts,

I have 2 queries.  I want to add the "TotalBeverageCost" column into the first query. If the LocationID      and CompanyID matches then put the "TotalBeverageCost" in a new column in the output of query1.      Please help!!

Thanks in advance.
This is my module:

Imports MySql.Data.MySqlClient
Module dbModule
    Public conn As New MySqlConnection
    ' Public edzon As String
    Public Sub dbConnect()
            If conn.State = ConnectionState.Closed Then
                'ESM Connection
                conn.ConnectionString = "server=;userid=elitescanning;password=ElItE123!@#ScAnNiNg;database=msd"

                'SMT Connection
                'conn.ConnectionString = "server=;userid=elitescanning;password=ElItE123!@#ScAnNiNg;database=msd"

            End If
        Catch ex As Exception
        End Try

    End Sub
End Module

Open in new window

How to save image and when I search the ID Number in from database, His,Her picture will display???

When a user clicks on the edit button of a gridview in asp.net, VB.NET the error thrown is an invalid DateTime exception. I need to handle this but unsure of how. Here is the asp.net inline code.

Text='<%#Convert.ToDateTime(Eval("StartTime")).ToString("hh") %>' />:<asp:TextBox ID="txtStartMinute" runat="server" Width="20px" Text='<%# Convert.ToDateTime(Eval("StartTime")).ToString("mm") %>' />

Open in new window


Visual Basic.NET





Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to  Visual Basic pre-2002, it is not the same technology,