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

Hello experts. I have a view that contains a bunch of calculations. For example a small part of the code is listed below.

SELECT     dbo.tbl_Employee.Department, dbo.tbl_Employee.EmployeeNumber, dbo.tbl_Employee.FirstName, dbo.tbl_Employee.LastName,
                      ROUND((CASE WHEN [Supp Dent Enrolled] = 'True' THEN (CASE WHEN ([Supp Dent] = 8.08) THEN (16.14 / 160) WHEN ([Supp Dent] = 24.96) THEN (16.16 / 160)
                      WHEN ([Supp Dent] = 24.72) THEN (16.16 / 160) WHEN ([Supp Dent] = 44.61) THEN (16.16 / 160) ELSE (0) END) ELSE 0 END), 4) AS SuppDental,
                      ROUND((CASE WHEN [Supp Vision Enrolled] = 'True' THEN (2.54 / 160) ELSE 0 END), 4) AS SuppVision, (CASE WHEN ([HDHP Enrolled] = 1) THEN (([HDHP Amt] / 12)
                      / 160) ELSE (0) END)
For now lets focus on Supp Dent = 8.08 and Supp Den = 24.96.

What I am looking to do is create some sort of admin screen in that allows me to view these figures and change them when needed thus updating the view (right now I am going into the view directly to update) How do I go about searching the statement to get the dollar amounts appear on the front end of my admin screen? I hope this makes sense. If not I attached a crude mock up.
What connection string would I use to access my local sql database on my computer. I remember using LocalDB etc
I'm using below code to access and read my excel file but it gives an error if my excel file open.

So how can i use it read only ? Any help would be grateful.

        Dim workbook As New ClosedXML.Excel.XLWorkbook("C:\Users\USER\Desktop\ChassisModel\genChassis.xlsx")
        Dim rowsNode = workbook.Worksheet("NodeList").RangeUsed().RowsUsed().Skip(1)

Open in new window

Using Framework...
     ASP.NET Regular Web Form

Using Code Behind... & JavaScript & JQuery

My Issue...
I Need VB.code replacement for the following JavaScript Function --
(JavaScript Function may not be Syntactically Correct Since I Slightly modified its structure)
function myFunc(RBG) {
   var rbGrp = RBG; 
   var myVal;
   var radioButtons = document.getElementsByName(rbGrp);
      for (var x = 0; x < radioButtons.length; x ++) {
        if (radioButtons[x].checked) {
	     myVal = radioButtons[x].id);
             return myVal;

Open in new window

This JavaScript Function is PASSED the GROUPNAME of a group of Radio buttons...

It loops thru all the individual radio buttons of that Group of buttons via that GROUPNAME...

and ihen it should return the one radio button that was selected...

I need this in Server Side code instead of client side JavaScript code...

I have already laid out 35 Groups of Radio buttons each with 2, 3 or 5 individual choices -- already built in my form so doing Radio Button List is now past as option

Any Experts have or can create this code equal to the JS code ??

thanks... CJ
In my home page I declare the two following variables at the top of the Default.aspx.vb page
I then load data to a grid using the next piece of code. My intention is to be able to sort the data by clicking
on the column header so I included the  GridView1_Sorting procedure shown further down at the bottom.
When I click on a header I get the following error in that procedure "DataTable must be set prior to using dataview."
Public Class Default
    Private objDV As New DataView
    Private dt As New DataTable
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Open in new window

    Sub Bind_Grid_to_Dataview(ByVal oGridView As GridView, ByVal oSQL As String)


            Dim cs As String = ConfigurationManager.ConnectionStrings("SSQL").ConnectionString
            Dim objCon As New SqlConnection 'Declaring connection object
            objCon.ConnectionString = cs
            'opening connection
            If objCon.State = ConnectionState.Closed Then
            End If
            'declaring new Data Adapter
            Dim objDA As New SqlDataAdapter
            objDA.SelectCommand = New SqlCommand(oSQL, objCon)
            Dim objDS As New DataSet
            Call oCheck_DataSet_For_Blank_Columns(objDS)
            'Below i am creating a default view of the Data Set
            objDV = objDS.Tables(0).DefaultView
            oGridView.DataSource = objDV

        Catch ex As Exception
            Response.Write(ex.Message & " dr2")
        End Try
    End Sub

Open in new window

   Private Sub GridView1_Sorting(sender As Object, e As GridViewSortEventArgs) Handles GridView1.Sorting

            objDV.Sort = e.SortExpression
            GridView1.DataSource = objDV
        Catch ex As Exception
            Response.Write(ex.Message & " Gridview Sorting Error 4")
        End Try

    End Sub

Open in new window

Installed SQL Server EXPRESS 2014 to my local desktop -

Created SQL Server AUTH hybrid login

Created a User Name and Password for connection string and gave them every permission i could find for both Server and Database I created

Created New DBase
Name: HousingAuthority

Created a table
Name: dbo.tblApplication

See uploaded image file with these names...

with 4 fields ID, FirstName_1, LastName_1, datetime field

See web page code below... that runs on visual studio local host server (needs better web config error handling too)

Insert Into code fired from button not working and web page not showing error...

<%@ Page Language="VB" AutoEventWireup="false" Debug="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data"%>\
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub

    Private Sub SubmitEM_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim con As New SqlConnection : Dim cmd As New SqlCommand
            con.ConnectionString = "Data Source=MY64BIT-PC\SQLEXPRESS;Initial Catalog=HousingAuthority;Persist Security Info=True;User ID=ABC;Password=XYZ"
            cmd.Connection = 

Open in new window

Hello I'm using below code to color True, False and NaN(not Applicable) strings to check what's wrong or OK.

My code works but it seems it's not logic approach to do that. If you have any experience i'd be grateful.

        Private Shared Sub ColorCells(ByVal dgv As DataGridView)
            If dgv.Rows.Count > 0 Then
                For i = 0 To dgv.Rows.Count - 1
                    For j = 0 To dgv.ColumnCount - 1
                        Select Case dgv.Rows(i).Cells(j).Value.ToString
                            Case "True"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Green
                            Case "False"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Red
                                dgv.Rows(i).Cells(0).Style.BackColor = Color.Red
                            Case "NaN"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Orange
                            Case Else
                        End Select
            End If
        End Sub

Open in new window

This kind of code delete all files in directory if cheked

          If chkDeleteSourceFiles.Checked Then
                For i As Integer = 0 To oFiles.Length - 1
                    Dim sFromFilePath As String = oFiles(i)
                    If IO.File.Exists(sFromFilePath) Then
                        Catch ex As Exception
                            txtOutput.Text += "No se puede borrar " & sFromFilePath &
                             ", " & ex.Message & vbCrLf
                        End Try
                    End If
            End If

Open in new window

That is a mess...
I need if is cheked only delete PDF files.
could you help me ?
I'm working on application which requires different type of inputs and i'm storing that required files and folder in my "Release" output folder.

Also i'm using that paths in mycodes like below format;

 Dim dbDir As String = Path.Combine(Environment.CurrentDirectory, My.Settings.str__data_dir, My.Settings.str__data_db)

Open in new window

In fact when i'm running in "Release" , Environment.CurrentDirectory is D:\TestCode but after i published the code all my paths is changed to RoamingData folder as you can see on error message when my application didn't found the path.

After that  i asked a question and realize i shouldn't built my path structure to Environment.CurrentDirectory.

So now i wonder when we're installing a commerical software that comes with several folder structure(like below image), what's the approach that programs use this directories.

I'm asking this because i'll be creating different folder structures and i want to access them in all cases.

Any help would be grateful.

System.Runtime.InteropServices.COMException: 'Provider cannot be found. It may not be properly installed.'

I know that this issue appears regularly on various sites but it can be an annoyance when the answer isn't obvious.
I have a VB.Net project that connects to an Excel spreadsheet and also a SQL database. The Database is updated with data from one of the Excel columns.
My project runs on some Windows 7 and / or Windows 10 machines but not on others giving the message above. It does successfully run on a Windows 10 64bit. There is a mix of 32/64 bit clients machines and SQL2014 is on a 64 bit server.
Annoyingly, I cannot get the project to run on my newly built Windows 10 in VS 2017 15.9.11
Office version is 365 Pro Plus 1904 build 11601.20144
Project references ADODB ActiveX data Objects 2.8 Library, Office 16.0 Object Library, Excel 16.0 Object Library amongst others.
The connection string is:
<add name="FloydConnectionString" connectionString="Data Source=FLOSERVSQL\FLOSQL;Initial Catalog=FloydProgs;User Id=floydproguser;Password=xcxcxcx;" providerName="System.Data.SqlClient"/>

What can I look at to get the client machines to run this project?

I have a DataGridView output like below;

As you can some values are same with the red-boxed columns and they values on the right side.

I want to sum-up that values like below;

What's the logic way to create a datagridview with like this structure which has source from another datagridview.
I'm getting some file info in my application and i'd like write them if have relative directory relationship in my application.

For example my directory: C:/files

If it's found file in;
C:/files/test1.pdf    'Output: ../test1.pdf
C:/files/190501/test2.pdf 'Output: ../190501/test2.pdf
C:/archive/180501/test3.pdf 'Output: C:/archive/180501/test3.pdf

I search on net and Path.GetRelativePath would fit my desire but it's not supported at .net 4.8 so Any help would be grateful.

I'm using my application in Release folder output and i create several folders in Release folder where my running exe belongs.

and i have lots of Path directions like below;

 Dim dbDir As String = Path.Combine(Environment.CurrentDirectory, My.Settings.str__data_dir, My.Settings.str__data_db)

Open in new window

all my Environment.CurrentDirectory returns different location after i published it and open there.

Is there a way to define these directories? Any help would be grateful.

I have a if-else structure in my code and i'm using below code. I don't know is there more easier and more logic structure for that so i need to ask you is there anybody have experience?

 If obj.intent.val = GetIntentStatus(0) Or obj.intent.val = GetIntentStatus(1) Or obj.intent.val = GetIntentStatus(2) Then

'Do something

End If

Open in new window

And GetIntentStatus is reading the combobox item's selected index.

        Private Shared Function GetIntentStatus() As Integer()
            Dim cbo As ToolStripComboBox = GUI.cboModuleBuild_list_intent
            If cbo.SelectedIndex = 0 Then
                Return {0, 0, 0}
            ElseIf cbo.SelectedIndex = 1 Then
                Return {1, 1, 1}
            ElseIf cbo.SelectedIndex = 2 Then
                Return {2, 2, 2}
            ElseIf cbo.SelectedIndex = 3 Then
                Return {0, 0, 1}
            ElseIf cbo.SelectedIndex = 4 Then
                Return {0, 1, 2}
                Return {0, 0, 0}
            End If
        End Function

Open in new window

As here you can see my obj.intent.val can equal 0,1,2 also i need as selected index 3 or 4 multiple conditions like obj.intent.val = 0 or obj.intent.val = 1 or obj.intent.val=2
I'm trying to use background worker but i didn't succeeded. It didin't perform anything. I'm a bit newbie about background worker topic.

So i'll be glad for any help. Thanks.

This is RunWorkerAsync() when i clicked my run button.
    Private Sub CheckRun(sender As Object, e As EventArgs) Handles cmdModuleCheck_run.Click
    End Sub

Open in new window

This is .DoWork() i'm calling it from another class
    Private Sub DoWorkCheck(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorkCheck.DoWork
    End Sub

Open in new window

This is my DoWork code which i runned from another class.
 Public Shared Sub RunCheck(ByVal mdl As IScrModel)

            Dim tView As TreeView = GUI.treCheckListMain
            Dim dgView As DataGridView = GUI.dgvCheckInfo

            For Each nodeParent As TreeNode In tView.Nodes
                For Each nodeChild As TreeNode In nodeParent.Nodes
                    If nodeChild.Checked = True Then
                        dgView.Rows.Add(nodeParent.Text, nodeChild.Text, "In queue")
                    End If

            If tView.Nodes.Item("nodBody").Nodes.Item("nodBodyComp").Checked = True Then
                Dim rowIndex As Integer = FindRowDgv(tView.Nodes.Item("nodBody").Text, tView.Nodes.Item("nodBody").Nodes.Item("nodBodyComp").Text)

Open in new window

Hi, i'm using below code to search some files in my directory with specific words. But there's a problem with it. It gives most of the time an error but for somewords it's ok.

Any help would be grateful, thank you.

    Private Sub cmdSearch_Click(sender As Object, e As EventArgs) Handles cmdSearch.Click
        If txtFilter.Text.Length > 4 Then
            Dim files As IEnumerable(Of String) = Directory.EnumerateFiles(txtDirectory.Text, "*.*", SearchOption.AllDirectories).Where(Function(s) s.Contains(txtFilter.Text) AndAlso (s.EndsWith("spck", StringComparison.OrdinalIgnoreCase) Or s.EndsWith(".buspck", StringComparison.OrdinalIgnoreCase)))
            lblWarning.Text = String.Empty
            If files.Count > 0 Then
                lblWarning.Text = files.Count & " files found!"
                For Each item In files
                    Dim fileArr() As String = Path.GetFileNameWithoutExtension(item).Split(New String() {"__"}, StringSplitOptions.None)
                    Dim typeArr() As String = fileArr(0).Split(New String() {"_"}, StringSplitOptions.None)
                    dgvResult.Rows.Add(typeArr(0), typeArr(1), fileArr(1), fileArr(2), fileArr(3), fileArr(4))
                lblWarning.Text = "No file found!"
            End If
            MsgBox("You should enter minimum 5 characters!")
        End If

    End Sub

Open in new window

I am trying to upload group of jpg files using
         dim thename as string="myfile.jpg"
         dim filename as string="c:\myfolder\myfile.jpg"
         'create request
         Dim mReq As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("" & thename), System.Net.FtpWebRequest)

                        With mReq
                            .Credentials = New System.Net.NetworkCredential(userid, Password)
                            .Method = System.Net.WebRequestMethods.Ftp.UploadFile
                        End With

                        'Read a file
                        Dim mFile() As Byte
                        mFile = System.IO.File.ReadAllBytes(fileName)

                        Dim mStream As System.IO.Stream = mReq.GetRequestStream()
                        mStream.Write(mFile, 0, mFile.Length)


An exception is raised in executing GetRequestStream() and the error is that file not found... It means that the  mreq could not create the file on the remote server.... I copied this code from the net, and nobody seems to have a problem... I must be doing something wrong... Help please. Thanks
Hi, I'm using below COM-interface function to get a list of used parameters in 3rd part program. Function output type is System.Array and item's like below;


Open in new window

Sample Output of model.getParameterList() as System.Array:

As in example F_x, F_y, F_z, M_x, M_y, M_z is related to each other so i'd like to check (e.g.) item starting with "$X_FR_TABUl" has F_x, F_y, F_z, M_x, M_y, M_z items. If all of them is existing it will return True else it will return False for each item.


Because as you can see $X_FR_FADAl_M_y is it missing.

Is there anyway to quick check these naming with best approach (maybe with LINQ) in ?

Any help would be grateful. Thanks.
I'm looking for any option or source for exporting user-scope settings to excel sheet and importing them from excel sheet.

Also is it possible to check in Visual Studio are they using/referenced in application?

Any help would be grateful.


I'm using below code to get user informations when user loads application and define it's user role.

I'm looking for is it possible to get Datarows with using LINQ in

Thank you.

        Public Shared Sub DefineUserType()

            Dim dbDir As String = Path.Combine(Environment.CurrentDirectory, My.Settings.str_autombs__data_dir, My.Settings.str_autombs__data_db)
            Dim dtUsers As DataTable
            Dim dtRoles As DataTable

            dtUsers = AccessMethods.ReadTable(dbDir, "Select * from Users")
            Dim drs As DataRow() = dtUsers.Select("[User Name]='" + Globals.UserName + "'")

            If drs.Length > 0 Then
                dtRoles = AccessMethods.ReadTable(dbDir, "Select * from UserRoles")
                Dim drRoles As DataRow() = dtRoles.Select($"Role='{drs(0)("Role")}'")
End If

Open in new window

For access connection i'm using below code.

Namespace Utility
    Public Class AccessMethods
        Public Shared Sub ExecuteQuery(ByVal pathFile As String, ByVal Sql As String)
            Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathFile
            Using myconnection As New OleDbConnection(constring)
                Using cmd As New OleDbCommand(Sql, myconnection)
                End Using
            End Using
        End Sub
        Public Shared Function ReadTable(ByVal pathFile As String, ByVal Sql As String) As DataTable
            Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathFile
            Dim dtb As New DataTable
            Using cnn As New OleDbConnection(constring)
                Using dad As New OleDbDataAdapter(Sql, cnn)
                End Using
            End Using
            Return dtb
        End Function
    End Class
End Namespace

Open in new window


I'm using COM-interface of third part tool in my application. I'm listing some property informations with like;

IBody is class and .mass, .length, .name is it's some of properties of IBody class but there are still other properties that i didn't list.

Now i wonder is there a way to list all properties which are belongs to that class in with their type(string, double, etc.)

I'll be glad if anyone has experience with that.
I've found a code for file searching at specific path for multiple filter below but i'd like to apply it for application? How is it possible to convert it to ?

var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories)
            .Where(s => s.Contains("test_file") );

Open in new window

Finally i would like to get list of files with full path which  are contains my string parameter.

I have Many PST and I need to read the emails and extract them any good example o code in
I had this question after viewing socket connect() & bind() together?.

I am an old VB6 programmer and I am trying to create a windows desktop app that communicates with a Linux server over TCP or UDP sockets.  I just downloaded .Net Community 2019 and I can't find anything on sockets for, just C#.  

How can I get the functionality of VB6 winsock.ocx in

I found useful  code that converts System.Array to String, but i couldn't succeed to implement to my application.

Any help would be great.


string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();

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,