• Home
  • Tools
    • Color Chart
  • Software
    • Windows tricks
      • Windows 11 Speed Up Tricks
      • Windows Command Prompt CMD
    • Android Phone
      • Android – Dangerous Settings to Turn Off
    • Projects
      • Copy Files
      • Php Autoscript
      • Web Tools
  • Payments
  • Notes
  • System Tips

Notes

ACCESS 2022 | Browsers | Css | Htacess | Html | Html5 | Javascript | Microsoft Excel | Mysql | Mysql Dumps | Php | Vb.net | VBscript | Windows <=8 | Windows >=10 | WP | WP Plugin | WP Themes | _Misc Software |

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ON
PRT
OFF

<- Look Inside Data
Conditions:
Order:
47 Language Operation Title
Keywords
Application
Code Languageid
Show Html
Show Iframe
Make Public
Viewed
Viewed Date
Vb.net Archive Email Remove Sub
email move
Outlook Mail Cleaner
Vb.net



7
02/26/2026
Vb.net Controls Combo Box Control
combo value archive example
Vb.net



4
07/27/2025
Vb.net Controls How To Use MSGBOX YES NO
message box
Decision
vate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim payed As Integer
Dim balance As Integer
Dim paying As Integer
Dim d As Integer
Dim c As Integer
Try

Dim ans As Integer
If TextBox7.Text = "" Or 0 Then

MsgBox("please enter amount", MsgBoxStyle.Critical)
Else
If TextBox6.Text = 0 Then

MsgBox("the student is fully payed", MsgBoxStyle.Critical)
Else
ans = MsgBox(" are you want to upadate the students payment? ", MsgBoxStyle.YesNo, "confirm ")
If MsgBoxResult.Yes Then


payed = Val(TextBox5.Text)
balance = Val(TextBox6.Text)
paying = Val(TextBox7.Text)
d = payed + paying
c = balance - paying
TextBox5.Text = d
TextBox6.Text = c

Dim SqlQuery = "UPDATE sample SET [Payed Amount] ='" & TextBox5.Text & "',Balance ='" & TextBox6.Text & "' WHERE ID = " & a & " ; "
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("student payment succesfully updated")
My.Computer.Audio.Play(My.Resources.CASHREG, AudioPlayMode.Background)
If TextBox6.Text = 0 Then
MsgBox("the student is now fully paid", MsgBoxStyle.Information)
TextBox7.Text = ""
Else

MsgBox("students current balance is " & Convert.ToString(TextBox6.Text))
LoadListView()
TextBox7.Text = ""
End If
Else
Exit Sub
End If
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Vb.net



0
12/11/2023
Vb.net Controls DoEvents In .NET
doevents
Developer
18

Application.DoEvents()
Vb.net



0
12/14/2023
Vb.net Controls Simple Drag Drop Example
drag drop mousedown
Developer
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Populate the ListBox with file paths
ListBox1.Items.Add("C:examplefile1.txt")
ListBox1.Items.Add("C:examplefile2.txt")
ListBox1.Items.Add("C:examplefile3.txt")

' Enable drag-and-drop functionality
ListBox1.AllowDrop = False
End Sub

Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Check if an item is selected
If ListBox1.SelectedItem IsNot Nothing Then
' Get the selected file path
Dim filePath As String = ListBox1.SelectedItem.ToString()

' Ensure the file exists before attempting to drag
If IO.File.Exists(filePath) Then
' Start the drag-and-drop operation
Dim files() As String = {filePath}
Dim dataObject As New DataObject(DataFormats.FileDrop, files)
ListBox1.DoDragDrop(dataObject, DragDropEffects.Copy)
End If
End If
End Sub
End Class
Key Points:
File Paths in ListBox: The ListBox should contain valid file paths that exist on the system.
Drag-and-Drop Operation: The DoDragDrop method is used to initiate the drag-and-drop operation, passing the file paths as a DataObject with the DataFormats.FileDrop format.
MouseDown Event: The drag operation starts when the user clicks and holds the mouse button on a selected item.
How It Works:
When the user clicks on an item in the ListBox and drags it, the application checks if the item is a valid file path.
If valid, the file path is passed to the DoDragDrop method, allowing the user to drop the file into File Explorer or other compatible applications.
This approach ensures a smooth drag-and-drop experience while maintaining proper validation of file paths.



I just dragged a file from my application to File Explorer using this code:
VB.NET:
Imports System.Collections.Specialized
Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
Dim data As New DataObject()
Dim filePaths As New StringCollection

filePaths.Add(Path.Combine(Application.StartupPath, "TestData.txt"))
data.SetFileDropList(filePaths)
DoDragDrop(data, DragDropEffects.Copy)
End Sub
If you are doing drag and drop just within your application then you can use whatever you want as that first argument to DoDragDrop and look for that same type when dropping. If you're doing it between applications then you do as I have here, i.e. create a DataObject, add data to it in the appropriate format(s) and then pass that to DoDragDrop. That will ensure that any application that supports drag and drop between applications will be able to access that data in the appropriate standard format.

That DataObject class also has SetText, SetImage and SetAudio methods for specific data types and a SetData method for everything else. They are the complementary methods to the e.Data.GetX methods you call in a DragDrop event handler.
Why is my data not saved to my database?



Certainly! If you want to drag items from a ListBox in VB.NET and treat them as files rather than strings, you can achieve this by handling the DragDrop and DragEnter events. Below is an example of how you can implement this:

Step-by-Step Implementation
Set up the ListBox for Drag-and-Drop:

Enable drag-and-drop for the ListBox.
Handle the MouseDown event to initiate the drag operation.
Handle DragEnter and DragDrop Events:

Ensure the target control accepts the dragged data.
Handle the drop operation to process the files.
Example Code

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Enable drag-and-drop for the ListBox
ListBox1.AllowDrop = True

' Add some items to the ListBox
ListBox1.Items.Add("C:pathtofile1.txt")
ListBox1.Items.Add("C:pathtofile2.txt")
End Sub

Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
If ListBox1.SelectedItem IsNot Nothing Then
' Start the drag-and-drop operation with the selected item as a file
ListBox1.DoDragDrop(New DataObject(DataFormats.FileDrop, New String() {ListBox1.SelectedItem.ToString()}), DragDropEffects.Copy)
End If
End Sub

Private Sub ListBox1_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox1.DragEnter
' Check if the data being dragged is a file
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub

Private Sub ListBox1_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox1.DragDrop
' Handle the drop operation
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each file As String In files
ListBox1.Items.Add(file)
Next
End If
End Sub
End Class
Explanation
Form Load Event:

Enables drag-and-drop for the ListBox.
Adds some initial file paths to the ListBox.
MouseDown Event:

Initiates the drag-and-drop operation when an item is selected and the mouse button is pressed.
DragEnter Event:

Checks if the data being dragged is a file and sets the appropriate effect.
DragDrop Event:

Handles the drop operation by adding the dropped files to the ListBox.
This code allows you to drag items from the ListBox and treat them as files, making it easier to integrate with other file-based operations. If you have any further questions or need additional customization, feel free to ask!

Example One Drag And Drop Controls Using Vb.Net
2.Drag and Drop operation-simple example
2.1. Basic drag & drop operation example
Let's look at some examples, starting with simple drag and drop operation. Create a Visual Basic. net windows application and design a form with control & Drag Drop event procedure as follows

To enable drag & drop for text

1. Place two textboxes and set Allowdrop property of a second textbox to true.
2. Add the following code

Private MouseIsDown As Boolean = False 'variable declaration

Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As _

System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown

'Set a flag to show that the mouse is down.

MouseIsDown = True

End Sub

Private Sub TextBox1_MouseMove(ByVal sender As Object, ByVal e As _

System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseMove

If MouseIsDown Then

' Initiate dragging.

TextBox1.DoDragDrop(TextBox1.Text,DragDropEffects.Copy)

End If

MouseIsDown = False

End Sub

Private Sub TextBox2_DragEnter(ByVal sender As Object, ByVal e As _

System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter

'Check the format of the data being dropped.

If (e.Data.GetDataPresent(DataFormats.Text)) Then

' Display the copy cursor.

e.Effect = DragDropEffects.Copy

Else

' Display the no-drop cursor.

e.Effect = DragDropEffects.None

End If

End Sub

Private Sub TextBox2_DragDrop(ByVal sender As Object, ByVal e As _

System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop

'Paste the text.

TextBox2.Text = e.Data.GetData(DataFormats.Text)

End Sub
In the above example, the MouseDown event is used to set a flag showing that the mouse is down, and then the DoDragDrop method is called in the MouseMove event. Although you could initiate the drag in the MouseDown event, doing so would create undesirable behavior: Every time a user clicks the control, the no-drag cursor would be displayed.

T
Vb.net



4
05/25/2025
Vb.net Customizing How To: Rename A File In Visual Basic
rename file
You don't need to mention the complete file path in newFileName parameter, just mention new file name here otherwise you will get ArgumentException.

Dim filePath As String = "C:fingerprint1"

If File.Exists(filePath) Then

Dim strNewFileName As String = "Fingerprint221"

My.Computer.FileSystem.RenameFile(filePath, strNewFileName)

End If
See also
Use the RenameFile method of the My.Computer.FileSystem object to rename a file by supplying the current location, file name, and the new file name. This method cannot be used to move a file; use the MoveFile method to move and rename the file.

To rename a file
Use the My.Computer.FileSystem.RenameFile method to rename a file. This example renames the file named Test.txt to SecondTest.txt.

VB

Copy
' Change "c:test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:Test.txt", "SecondTest.txt")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File system - Processing Drives, Folders, and Files. For more information, see Code Snippets.
Vb.net



0
12/09/2023
Vb.net Customizing Code Behinnd MR Button Webtools
chr MR
Web Tools
? seperates values
chr(032032?chr(032 use ascii
"bof" BEGIN OF FILE
"eof" END OF FILE
"lf" remove double CrLf
"td" Replace tabs with dash
"ts" tab to spaces
"tc" tab to comma
"lfc" replace line feeds with commas
"lb-" Replace line breaks with -
"{GET}" EXTRACT BETWEEN { }
"{DEL}" 'Delete BETWEEN { }
Vb.net



0
11/29/2024
Vb.net Customizing Running A 3rd Party Application
computer name shell write
3rd Party Software
ou should consider using Process.Start instead of Shell, as Shell is a holdover from the VB 6 days and Process.Start is built into the .NET Framework.

Here is an example of running Microsoft Word via the command line, passing it parameters, including file name and any flags:

Sub Main()
OpenMicrosoftWord("C:UsersSamDocumentsOfficeGears.docx")
End Sub

'''
''' Open the path parameter with Microsoft Word.
'''

Private Sub OpenMicrosoftWord(ByVal f As String)
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "WINWORD.EXE"
startInfo.Arguments = f
Process.Start(startInfo)
End Sub
==============================
old school
Dim R As String = My.Computer.Name '
R = GetIni("Database", R, INI)
If R = "" Then
WriteIni("Database", My.Computer.Name, "Dropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI)
Shell("write.exe " + INI, vbNormalFocus) : Exit Sub
End If
Vb.net



2
07/27/2025
Vb.net Customizing Close Running Processes
application close running
Windows

VB.Net Close window by title



Top Answer

Answered Jun 29, 2012 · 6 votes

Try using something like this. using Process.MainWindowTitle


to get the Title Text and Process.CloseMainWindow


to close down the UI, its a little more graceful than killing the Process.

Note: Contains does a case-sensitive search

Imports System.Diagnostics
Module Module1
Sub Main()
Dim myProcesses() As Process = Process.GetProcesses
For Each p As Process In myProcesses
If p.MainWindowTitle.Contains("Notepad") Then
p.CloseMainWindow()
End If
Next
End Sub
End Module

Display processes running


Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click
File1.Items.Clear()
For Each p In Process.GetProcesses
If p.MainWindowTitle <> "" Then
'File1.Items.Add(p.MainWindowTitle + "..running")
File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]")
End If
Next
End Sub
Vb.net



1
07/21/2025
Vb.net Customizing Debug Properties Of Project
signing compile debug settings
Vb 22
under the menu "debug" look for "xxxx debug properties"

Application
compile
debug
references
resources
services
Settings
signing
my extension's
security
publish
code analysis.
Vb.net



0
02/05/2025
Vb.net Customizing Handling Directories
directory
Developer

Creating Directories


If Not System.IO.Directory.Exists(YourPath) Then
System.IO.Directory.CreateDirectory(YourPath)
End If
Vb.net



0
03/23/2025
Vb.net Customizing Move Emails From Multiple Accounts To An Outlook Data File
multiple accounts move email flag
OUTLOOK
Imports Microsoft.Office.Interop.Outlook

Module Module1
Sub Main()
' Initialize Outlook application
Dim outlookApp As New Application()
Dim namespaceMAPI As [NameSpace] = outlookApp.GetNamespace("MAPI")

' Specify the path to the Outlook Data File (PST)
Dim pstFilePath As String = "C:PathToYourDataFile.pst"
Dim pstDisplayName As String = "Archived Emails"

' Add the PST file to Outlook if not already added
Try
namespaceMAPI.AddStore(pstFilePath)
Catch ex As Exception
Console.WriteLine("PST file already added or an error occurred: " & ex.Message)
End Try

' Get the root folder of the PST file
Dim pstRootFolder As MAPIFolder = namespaceMAPI.Folders(pstDisplayName)

' Loop through all accounts in Outlook
For Each account As Account In namespaceMAPI.Accounts
Console.WriteLine("Processing account: " & account.DisplayName)

' Access the Inbox folder of the account
Dim inboxFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox")

' Create a subfolder in the PST file for this account
Dim accountFolder As MAPIFolder = pstRootFolder.Folders.Add(account.DisplayName)

' Move emails from the Inbox to the PST subfolder
For i As Integer = inboxFolder.Items.Count To 1 Step -1
Try
Dim mailItem As MailItem = TryCast(inboxFolder.Items(i), MailItem)
If mailItem IsNot Nothing Then
mailItem.Move(accountFolder)
Console.WriteLine("Moved email: " & mailItem.Subject)
End If
Catch ex As Exception
Console.WriteLine("Error moving email: " & ex.Message)
End Try
Next
Next

Console.WriteLine("Emails moved successfully!")
End Sub
End Module
Key Points:
Add Reference: Add a reference to the Microsoft.Office.Interop.Outlook library in your project.
PST File Path: Replace "C:PathToYourDataFile.pst" with the actual path to your PST file.
Permissions: Ensure you have the necessary permissions to access the accounts and move emails.
Error Handling: The code includes basic error handling, but you may need to enhance it for production use.
Outlook Version: This code is compatible with Outlook versions that support the Interop library.
Notes:
Running this code may require administrative privileges.
Ensure Outlook is properly configured and running on the machine.
Test the script in a safe environment before using it on live data to avoid accidental data loss.

=============== option =================

' Initialize Outlook application
Dim outlookApp As New Outlook.Application()
Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI")

' Loop through all accounts
For Each account As Outlook.Account In namespaceMAPI.Accounts
MsgBox(account.DisplayName)
'Console.WriteLine($"Processing account: {account.DisplayName}")

' Access the Inbox folder for the account
Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox")

' Specify the target folder (e.g., "Processed Emails")
'Dim targetFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Processed Emails")


Next

'Console.WriteLine("Emails moved successfully!")

======= flag status ==================

Determining if an email is "flagged" in VB.NET typically refers to checking the follow-up flag status of an email within an application like Microsoft Outlook. This involves interacting with the Outlook object model.
Here's a general approach using the Outlook Object Model in VB.NET:

Reference the Outlook Library: In your VB.NET project, add a reference to the Microsoft Outlook Object Library.
Create an Outlook Application Object:

Code

Dim olApp As New Outlook.Application()

Get the Namespace and Folder.
Code

Dim olNS As Outlook.Namespace = olApp.GetNamespace("MAPI")
Dim inboxFolder As Outlook.MAPIFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

Iterate Through Mail Items.
Code

For Each item As Object In inboxFolder.Items
If TypeOf item Is Outlook.MailItem Then
Dim mailItem As Outlook.MailItem = CType(item, Outlook.MailItem)

' Check the FlagStatus property
If mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagged Then
' The email is flagged
Console.WriteLine($"Email: {mailItem.Subject} is flagged.")
ElseIf mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagComplete Then
' The email flag is marked complete
Console.WriteLine($"Email: {mailItem.Subject} flag is complete.")
Else
' The email is not flagged
Console.WriteLine($"Email: {mailItem.Subject} is not flagged.")
End If
End If
Next

Explanation:

Outlook.OlFlagStatus.olFlagged: Indicates the email has been flagged for follow-up.
Outlook.OlFlagStatus.olFlagComplete: Indicates the follow-up flag has been marked as complete.
Outlook.OlFlagStatus.olNotFlagged: Indicates no follow-up flag is set.

Important Considerations:

Outlook Installation:
This approach requires Microsoft Outlook to be installed on the machine where the VB.NET application is running.
Security Prompts:
Outlook may display security prompts when your application attempts to access its data.
Error Handling:
Implement robust error handling to manage potential issues like Outlook not being open or access denied.
Alternatives:
For scenarios where Outlook isn't installed or direct interaction is not desired, consider using APIs like Microsoft Graph API (if working with Outlook 365) to access mailbox data and flag status.
Vb.net



3
08/02/2025
Vb.net Customizing Control Window State Of App
maximize all programs minimize
Outlook Mail Cleaner
automatically minimize a window in VB.NET, you can set the WindowState property of the form to FormWindowState.Minimized. This can be done in various scenarios, such as when the form loads, in response to a user action (like clicking a button), or based on a timer.
1. Minimizing the Current Form:
To minimize the form where the code is executed:
Code

Me.WindowState = FormWindowState.Minimized
This line of code can be placed within an event handler, such as a button click event or a form load event.
2. Minimizing All Active Forms:
To minimize all forms currently open in your application:
Code

For Each frm As Form In Application.OpenForms
frm.WindowState = FormWindowState.Minimized
Next frm
This code iterates through the Application.OpenForms collection and sets the WindowState of each form to Minimized.
3. Minimizing an External Application Window (Advanced):
Minimizing an external application's window requires using Windows API functions. This involves obtaining the window handle of the target application and then using functions like ShowWindow to manipulate its state. This is a more complex approach and typically involves PInvoke to call unmanaged code.
Example for a specific event:
To minimize the form when a specific button is clicked:
Code

Private Sub btnMinimize_Click(sender As Object, e As EventArgs) Handles btnMinimize.Click
Me.WindowState = FormWindowState.Minimized
End Sub

Maximize all apps


Imports System.Runtime.InteropServices
Module ModConnection

' Import the ShowWindow function from user32.dll

Public Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
End Function

' Constants for ShowWindow

Public Const SW_SHOWNORMAL = 1
Public Const SW_SHOWMAXIMIZED = 3
Public Const SW_SHOWMINIMIZED = 6

your function calls

Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click

File1.Items.Clear()
For Each p In Process.GetProcesses
If p.MainWindowTitle <> "" Then
'File1.Items.Add(p.MainWindowTitle + "..running")
File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]")
ShowWindow(p.MainWindowHandle, SW_SHOWMAXIMIZED)
End If
Next
End Sub
Vb.net



0
10/19/2025
Vb.net Customizing Control Top Left Width & Height Of Form
form top left width height
Form Size
Public Sub New()
' Set form title
Me.Text = "Form Position and Size Example"

' Set form position (Top, Left) and size (Width, Height)
Me.StartPosition = FormStartPosition.Manual ' Required to manually set position
Me.Left = 200 ' Distance from left edge of screen
Me.Top = 150 ' Distance from top edge of screen
Me.Width = 800 ' Form width in pixels
Me.Height = 600 ' Form height in pixels

' Add a button to display current values
Dim btnShowInfo As New Button()
btnShowInfo.Text = "Show Form Info"
btnShowInfo.Dock = DockStyle.Fill
AddHandler btnShowInfo.Click, AddressOf ShowFormInfo
Me.Controls.Add(btnShowInfo)
End Sub

Private Sub ShowFormInfo(sender As Object, e As EventArgs)
' Display current position and size
MessageBox.Show(
$"Top: {Me.Top}" & vbCrLf &
$"Left: {Me.Left}" & vbCrLf &
$"Width: {Me.Width}" & vbCrLf &
$"Height: {Me.Height}",
"Form Info"
)
End Sub


Public Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New MainForm())
End Sub
End Class



MsgBox(My.Computer.Screen.WorkingArea.Height)
MsgBox(My.Computer.Screen.WorkingArea.Width)
MessageBox.Show(
$"Top: {Me.Top}" & vbCrLf &
$"Left: {Me.Left}" & vbCrLf &
$"Width: {Me.Width}" & vbCrLf &
$"Height: {Me.Height}",
"Form Info"
)
Vb.net



1
11/17/2025
Vb.net Customizing Line Numbers On A Rich Textbox
line number textbox
Textbox
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
Inherits Form

Private WithEvents rtb As New RichTextBox()
Private WithEvents pnlLineNumbers As New Panel()

Public Sub New()
' Form setup
Me.Text = "RichTextBox with Line Numbers"
Me.Size = New Size(800, 600)

' Panel for line numbers
pnlLineNumbers.Dock = DockStyle.Left
pnlLineNumbers.Width = 50
pnlLineNumbers.BackColor = Color.LightGray
AddHandler pnlLineNumbers.Paint, AddressOf pnlLineNumbers_Paint

' RichTextBox setup
rtb.Dock = DockStyle.Fill
rtb.Font = New Font("Consolas", 10)
rtb.WordWrap = False
rtb.ScrollBars = RichTextBoxScrollBars.ForcedBoth

' Add controls
Me.Controls.Add(rtb)
Me.Controls.Add(pnlLineNumbers)
End Sub

' Redraw line numbers when text changes or scrolls
Private Sub rtb_TextChanged(sender As Object, e As EventArgs) Handles rtb.TextChanged
pnlLineNumbers.Invalidate()
End Sub

Private Sub rtb_VScroll(sender As Object, e As EventArgs) Handles rtb.VScroll
pnlLineNumbers.Invalidate()
End Sub

' Draw line numbers
Private Sub pnlLineNumbers_Paint(sender As Object, e As PaintEventArgs)
e.Graphics.Clear(pnlLineNumbers.BackColor)

Dim firstIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, 0))
Dim firstLine As Integer = rtb.GetLineFromCharIndex(firstIndex)

Dim lastIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, rtb.Height))
Dim lastLine As Integer = rtb.GetLineFromCharIndex(lastIndex)

Dim lineHeight As Integer = TextRenderer.MeasureText("A", rtb.Font).Height

Dim y As Integer = 0
For i As Integer = firstLine To lastLine
Dim lineNumber As String = (i + 1).ToString()
Dim size As Size = TextRenderer.MeasureText(lineNumber, rtb.Font)
e.Graphics.DrawString(lineNumber, rtb.Font, Brushes.Black,
pnlLineNumbers.Width - size.Width - 5, y)
y += lineHeight
Next
End Sub

' Entry point

Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
Vb.net



1
12/08/2025
Vb.net Database Create Read Only Recordset
create recordset error list box
LISTBOX
Vb.net



2
09/09/2023
Vb.net Database Delete A Record From A DAO Recordset
delete recordset
Vb.net



0
10/09/2022
Vb.net Database Extract Data From A Record In A DAO Recordset
extreact recordset
Vb.net



2
09/09/2023
Vb.net Database Using The Datagridview Control
datagrid access mdb view
access developer
Vb.net



4
02/06/2025
Vb.net Database Creating A Databse Driven Drop Down
combo mdb drop down list
access developer

Module ConnDB() in Using The Datagridview Control


Private Sub LoadMultipleCombo()
Try
sqL = "SELECT [replaceid],[title],[section_code] FROM [mulitreplace] order by [title]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
'dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim Table_ As String = "mulitreplace ORDER BY title"
Dim ds As New DataSet
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, Table_)
conn.Close()
Dim t1 As DataTable = ds.Tables(Table_)
txMultiAction.Items.Clear()
txMultiAction.ValueMember = "replaceid"
txMultiAction.DisplayMember = "title"
txMultiAction.DataSource = ds.Tables(Table_)
End Sub


Function LoadMultiData()
ConnDB()
Dim Table_ As String = "mulitreplace WHERE replaceid=" + Str(txMultiAction.SelectedValue)
Dim query As String = "SELECT * FROM " & Table_
Dim ds As New DataSet
Dim cmd As New OleDbCommand(query, conn)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, Table_)
conn.Close()
Dim t1 As DataTable = ds.Tables(Table_)
Dim row As DataRow
Dim Item(2) As String
For Each row In t1.Rows
Item(0) = row(0)
Item(1) = row(1)
Item(2) = row(2)

Next
Return Item(2)
End Function
Vb.net



2
02/06/2025
Vb.net Database Inserting Records Into Database And Data Grid
add insert update sql
Web Tools Create & Update Records
Imports System.IO
Imports System.Text
Imports System.Data.OleDb

Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click
Select Case table_selected
Case "copytext"
Try
sqL = "INSERT INTO [copy_it]([category],[copy_text],[notes]) VALUES ('" + txTitle.Text + "', '" + TXfield3.Text + "', '" + txSectionCode.Text + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txTitle.Text, TXfield3.Text, txSectionCode.Text)
Case "directorycopy"
Try
sqL = "INSERT INTO [directory_copy]([prefix],[directory]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text)
Case "multireplace"
Try
sqL = "INSERT INTO [mulitreplace]([title],[section_code]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text)
Case "filepaths"
Try
sqL = "INSERT INTO [file_paths]([file_path],[computer]) VALUES ('" + txSectionCode.Text + "','" + My.Computer.Name + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txSectionCode.Text)
Case "emailmoved"
Try
sqL = "INSERT INTO [move_email]([move_to],[archive],[subject_filter]) VALUES ('" + txTitle.Text + "', '" + TXfield3.Text + "', '" + txSectionCode.Text + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text, TXfield3.Text)
Case "emailfiltered"
Try
sqL = "INSERT INTO [Filtered_email]([importance],[email]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
DataGridView1.Rows.Add(0, txSectionCode.Text, txTitle.Text)
End Select


Private Sub btUpdate_Click(sender As Object, e As EventArgs) Handles btUpdate.Click
Dim update As DataGridViewRow = DataGridView1.SelectedRows(0)
If txReplaceid.Text = "0" Then MsgBox("You cannot edit new records without refresh.") : Exit Sub
Select Case table_selected
Case "copytext"
update.Cells(1).Value = txTitle.Text
update.Cells(2).Value = TXfield3.Text
update.Cells(3).Value = txSectionCode.Text
Try
sqL = "UPDATE [copy_it] SET [category]='" + txTitle.Text + "',[copy_text]='" + TXfield3.Text + "',[notes]='" + txSectionCode.Text + "' WHERE [copyID]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Case "multireplace"
update.Cells(1).Value = txTitle.Text
update.Cells(2).Value = txSectionCode.Text
Try
sqL = "UPDATE [mulitreplace] SET [title]='" + txTitle.Text + "',[section_code]='" + txSectionCode.Text + "' WHERE [replaceid]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Case "directorycopy"
update.Cells(1).Value = txTitle.Text
update.Cells(2).Value = txSectionCode.Text
Try
sqL = "UPDATE [directory_copy] SET [prefix]='" + txTitle.Text + "',[directory]='" + txSectionCode.Text + "' WHERE [directoryID]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Case "filepaths"
update.Cells(1).Value = txSectionCode.Text
Try
sqL = "UPDATE [file_paths] SET [file_path]='" + txSectionCode.Text + "' WHERE [pathID]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Case "emailfiltered"
update.Cells(2).Value = txTitle.Text
update.Cells(1).Value = txSectionCode.Text
Try
sqL = "UPDATE [Filtered_email] SET [importance]='" + txTitle.Text + "',[email]='" + txSectionCode.Text + "' WHERE [emailID]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Case "emailmoved"
update.Cells(1).Value = txTitle.Text
update.Cells(3).Value = TXfield3.Text
update.Cells(2).Value = txSectionCode.Text
Try
sqL = "UPDATE [move_email] SET [move_to]='" + txTitle.Text + "',[archive]='" + TXfield3.Text + "',[subject_filter]='" + txSectionCode.Text + "' WHERE [moveID]=" + txReplaceid.Text
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Select
Vb.net



2
07/23/2025
Vb.net Database Loading Records From Database Into Data Grid
data grid datagrid
Web Tools Load Grid With Mdb
Imports System.IO
Imports System.Text
Imports System.Data.OleDb

Private Sub btRefresh_Click(sender As Object, e As EventArgs) Handles btRefresh.Click
txReplaceid.Text = "" : txTitle.Text = "" : txSectionCode.Text = "" : DataGridView1.Columns.Clear()
Select Case table_selected
Case "copytext"
txSectionCode.Height = 100 : TXfield3.Visible = True : txTitle.Visible = True
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("copyID", "copyID") : .Columns.Add("category", "category") : .Columns.Add("copy_text", "copy_text") : .Columns.Add("notes", "notes")
.Columns(0).Visible = False
.Columns(1).HeaderText = "Category" : .Columns(1).Width = 120
.Columns(2).HeaderText = "TEXT" : .Columns(2).Width = 420
.Columns(3).HeaderText = "Notes" : .Columns(3).Width = 200
Try
sqL = "SELECT [copyID],[category],[copy_text],[notes] FROM [copy_it] ORDER BY [category],[copy_text]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
Case "filepaths"
txSectionCode.Height = 100 : TXfield3.Visible = False
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("pathID", "pathID") : .Columns.Add("file_path", "file_path")
.Columns(0).Visible = False : txTitle.Visible = False
.Columns(1).HeaderText = "File Path"
.Columns(1).Width = 1200
Try
sqL = "SELECT [pathID],[file_path] FROM [file_paths] WHERE [computer]='" + My.Computer.Name + "' ORDER BY [file_path]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
Case "multireplace"
txSectionCode.Height = 300 : TXfield3.Visible = False
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("switchid", "switchid") : .Columns.Add("position", "Position") : .Columns.Add("code", "code") : .Columns.Add("Description", "Description")
.Columns(0).Visible = False : txTitle.Visible = True
.Columns(1).HeaderText = "Title"
.Columns(2).HeaderText = "Code"

.Columns(1).Width = 300 : .Columns(2).Width = 1200
Try
sqL = "SELECT [replaceid],[title],[section_code] FROM [mulitreplace] order by [title]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1), dr(2))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
Case "directorycopy"
txSectionCode.Height = 300 : TXfield3.Visible = False
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("directorid", "DirectoryID") : .Columns.Add("prefix", "Prefix") : .Columns.Add("directory", "Directory") ' .Columns.Add("Description", "Description")
.Columns(0).Visible = False : txTitle.Visible = True
.Columns(1).HeaderText = "Prefix"
.Columns(2).HeaderText = "Directory"
.Columns(1).Width = 300 : .Columns(2).Width = 1200
Try
sqL = "SELECT [directoryID],[prefix],[directory] FROM [directory_copy] order by [prefix]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1), dr(2))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
Case "emailfiltered"
txSectionCode.Height = 100 : TXfield3.Visible = False
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("emailID", "ID") : .Columns.Add("email", "Email Filter") : .Columns.Add("importance", "Rate") ' .Columns.Add("Description", "Description")
.Columns(0).Visible = False : txTitle.Visible = True
.Columns(1).HeaderText = "Email Filter"
.Columns(2).HeaderText = "Rated"
.Columns(1).Width = 400 : .Columns(2).Width = 100
Try
sqL = "SELECT [emailID],[email],[importance] FROM [Filtered_email] ORDER BY [email]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1), dr(2))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
Case "emailmoved"
txSectionCode.Height = 100 : TXfield3.Visible = True : txTitle.Visible = True
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.Width = 1150
.Columns.Add("moveID", "ID") : .Columns.Add("move_to", "Move To") : .Columns.Add("subject_filter", "Subject Phrase") : .Columns.Add("archive", "Archive")
.Columns(0).Visible = False
.Columns(1).HeaderText = "Move To" : .Columns(1).Width = 250
.Columns(2).HeaderText = "Subject Phrase" : .Columns(2).Width = 600
.Columns(3).HeaderText = "Archive" : .Columns(3).Width = 200
Try
sqL = "SELECT [moveID],[move_to],[subject_filter],[archive] FROM [move_email] ORDER BY [move_to],[subject_filter]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
.Rows.Clear()
Do While dr.Read
.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
End Select

End Sub

=============== mouse event ==============
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0)
Select Case table_selected
Case "copytext"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txTitle.Text = dr.Cells(1).Value.ToString()
TXfield3.Text = dr.Cells(2).Value.ToString()
Clipboard.SetText(TXfield3.Text, TextDataFormat.UnicodeText)
txSectionCode.Text = dr.Cells(3).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
Case "directorycopy"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txTitle.Text = dr.Cells(1).Value.ToString()
txSectionCode.Text = dr.Cells(2).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
Case "multireplace"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txTitle.Text = dr.Cells(1).Value.ToString()
txSectionCode.Text = dr.Cells(2).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
Case "filepaths"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txSectionCode.Text = dr.Cells(1).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
Case "emailmoved"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txTitle.Text = dr.Cells(1).Value.ToString()
TXfield3.Text = dr.Cells(3).Value.ToString()
txSectionCode.Text = dr.Cells(2).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
Case "emailfiltered"
Try
txReplaceid.Text = dr.Cells(0).Value.ToString()
txSectionCode.Text = dr.Cells(1).Value.ToString()
Catch ex As Exception
MsgBox(Err.ToString)
End Try
End Select


End Sub
Vb.net



4
09/08/2025
Vb.net Database ConnectionMod.vb
add update sql access radio
Web Tools Database
Imports System.Data.OleDb

Module ModConnection
Public cur As Form
Public dt As DataTable
Public conn As OleDbConnection
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Public da As OleDbDataAdapter
Public ds As DataSet
Public sqL As String
Public Sub ConnDB()
Dim R As String = My.Computer.Name '
R = GetIni("Database", R, INI)
If R = "" Then
WriteIni("Database", My.Computer.Name, "Dropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI)
Shell("write.exe " + INI, vbNormalFocus) : Exit Sub
End If
'C:UserssteveDropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb"
Try
Dim connectionString As String = "Provider=Microsoft.jet.oledb.4.0;Data Source=" + R
'Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + R
conn = New OleDbConnection(connectionString)
'conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath() & "beer.mdb;")
'conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Databasephone.mdb;Jet OLEDB:Database Password = escobar;")
conn.Open()
Catch ex As Exception
MsgBox("Failed in Connecting to database")
End Try
End Sub
Public Function getDataTable(ByVal SQL As String) As DataTable
ConnDB()
Dim cmd As New OleDbCommand(SQL, conn)
Dim dt As New DataTable
Dim da As New OleDbDataAdapter(cmd)
da.Fill(dt)
Return dt
End Function
End Module

-------------- radio button test -------------------------

Private Sub rbFilePaths_CheckedChanged(sender As Object, e As EventArgs) Handles rbFilePaths.CheckedChanged
If rbFilePaths.Checked = True Then table_selected = "filepaths" : btRefresh_Click(sender, e)
End Sub

Private Sub rbMultireplace_CheckedChanged(sender As Object, e As EventArgs) Handles rbMultireplace.CheckedChanged
If rbMultireplace.Checked = True Then table_selected = "multireplace" : btRefresh_Click(sender, e)
End Sub

Private Sub txText_TextChanged(sender As Object, e As EventArgs) Handles txText.TextChanged

End Sub

Private Sub rbDirectoryCopy_CheckedChanged(sender As Object, e As EventArgs) Handles rbDirectoryCopy.CheckedChanged
If rbDirectoryCopy.Checked = True Then table_selected = "directorycopy" : btRefresh_Click(sender, e)
End Sub

Private Sub RBcopyText_CheckedChanged(sender As Object, e As EventArgs) Handles RBcopyText.CheckedChanged
If RBcopyText.Checked = True Then table_selected = "copytext" : btRefresh_Click(sender, e)
End Sub

Private Sub RBemailFiltered_CheckedChanged(sender As Object, e As EventArgs) Handles RBemailFiltered.CheckedChanged
If RBemailFiltered.Checked = True Then table_selected = "emailfiltered" : btRefresh_Click(sender, e)
End Sub

Private Sub RBemailMove_CheckedChanged(sender As Object, e As EventArgs) Handles RBemailMove.CheckedChanged
If RBemailMove.Checked = True Then table_selected = "emailmoved" : btRefresh_Click(sender, e)
End Sub

====== selected table =============
Select Case table_selected
Case "copytext"

Case "directorycopy"

Case "multireplace"

Case "filepaths"

Case "emailmoved"

Case "emailfiltered"

End Select
Vb.net



5
07/23/2025
Vb.net Files Directory Files Into A List Box Checking Drive Available
delete files directory drive listbox
Vb.net



2
09/09/2023
Vb.net Files Read And Write ENTIRE FILE
open read file write file entire
File Writing
[READ]
read entire file into string.
A = My.Computer.FileSystem.ReadAllText(Path.TREE2 + "/" + Explore.File1.Items(J).ToString, System.Text.Encoding.Default)
CODE1 = My.Computer.FileSystem.ReadAllText(Tree2 + Filename + "Code.txx")

[WRITE]
Dim CODE1 As String = My.Computer.FileSystem.ReadAllText(Tree2 + Filename + "Code.txx")
J = InStr(CODE1, "``") : CODE1 = Left(CODE1, J - 1)
For J = 0 To TMPA.Count - 1
If InStr(CODE1, "`" + TMPA(J) + "`") = 0 Then NotFound = True : CODE1 = CODE1 + "`" + TMPA(J) + "`" + vbCR
Next
CODE1 = CODE1 + "``" + vbCR
If NotFound = True Then My.Computer.FileSystem.WriteAllText(Tree2 + Filename + "Code.txx", CODE1, append:=False)
Vb.net



1290
09/09/2023
Vb.net Files Read Text File Line By Line & Write
read file line write append
Imports Microsoft.VisualBasic

Module Module1
Sub Main()
Dim filePath As String = "example.txt"
Dim fileNumber As Integer = FreeFile()

Try
' Open file for append using legacy VB method
FileOpen(fileNumber, filePath, OpenMode.Append) 'FileOpen(7, TREE3 + FLD(0, 0) + "_header.php", OpenMode.Output)
PrintLine(fileNumber, "This is a new line of text.")
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
FileClose(fileNumber)
End Try
End Sub
End Module



READ LINES FROM A TEXT FILE
Dim LineInput As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(Tree + "tabletempsave.txt")
Do Until LineInput.EndOfStream
A = LineInput.ReadLine : A = Trim(A)
LOOP

lineInput.close
=========================================
Shared Sub Main()
' Get an available file number.
Dim file_num As Integer = FreeFile()

' Open the file.
Dim file_name As String = "test.txt"
FileOpen(file_num, file_name, OpenMode.Input, OpenAccess.Read, OpenShare.Shared)

' Read the file's lines.
Do While Not EOF(file_num)
' Read a line.
Dim txt As String = LineInput(file_num)
Console.WriteLine(txt)
Loop

' Close the file.
FileClose(file_num)
End Sub
Vb.net



1352
09/09/2023
Vb.net Files Strip Html From Text
strip html strip tags browser
If you get html text from a browser you can read the clipboard as html

Imports System.Text.RegularExpressions

Module Module1

Sub Main()
' Input.
Dim html As String = "

There was a .NET programmer " +
"and he stripped the HTML tags.

"

' Call Function.
Dim tagless As String = StripTags(html)

' Write.
Console.WriteLine(tagless)
End Sub

'''
''' Strip HTML tags.
'''

Function StripTags(ByVal html As String) As String
' Remove HTML tags.
Return Regex.Replace(html, "<.*?>", "")
End Function

End Module
Vb.net



1009
09/09/2023
Vb.net Files Create A Copy Or Move A File In A Different Directory
copy files move files
File Management
' Copy the file to a new location without overwriting existing file.
My.Computer.FileSystem.CopyFile(
"C:UserFilesTestFilestestFile.txt",
"C:UserFilesTestFiles2testFile.txt")

' Copy the file to a new folder, overwriting existing file.
My.Computer.FileSystem.CopyFile(
"C:UserFilesTestFilestestFile.txt",
"C:UserFilesTestFiles2testFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

' Copy the file to a new folder and rename it.
My.Computer.FileSystem.CopyFile(
"C:UserFilesTestFilestestFile.txt",
"C:UserFilesTestFiles2NewFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

==================
overwrite defaults to false need to add ",true" inside the function

The My.Computer.FileSystem.MoveFile method can be used to move a file to another folder. If the target structure does not exist, it will be created.

To move a file
Use the MoveFile method to move the file, specifying the file name and location for both the source file and the target file. This example moves the file named test.txt from TestDir1 to TestDir2. Note that the target file name is specified even though it is the same as the source file name.

VB

Copy
My.Computer.FileSystem.MoveFile("C:TestDir1test.txt",
"C:TestDir2test.txt")
To move a file and rename it
Use the MoveFile method to move the file, specifying the source file name and location, the target location, and the new name at the target location. This example moves the file named test.txt from TestDir1 to TestDir2 and renames it nexttest.txt.

VB

Copy
My.Computer.FileSystem.MoveFile("C:TestDir1test.txt",
"C:TestDir2nexttest.txt",
FileIO.UIOption.AllDialogs,
FileIO.UICancelOption.ThrowException)
Vb.net



0
12/10/2023
Vb.net Files FILE MODIFICATION
file date newer
File Copy
Vb.net



0
11/17/2024
Vb.net Files File Drag Drop Listview
drag drop file 3rd party
Developer
12/31/25 ai search
To programmatically
drag multiple files from your VB.NET application and drop them onto a third-party application, you must prepare a DataObject in a standard format that other Windows programs can understand. The standard format for files is DataFormats.FileDrop.
Initiating the Drag Operation
In your VB.NET application, for the control you want to initiate the drag from (e.g., a Button or a ListView item), use the DoDragDrop method within a mouse event (like MouseDown):
vb.net
WEBTOOLS USING File1 control

Private Sub File1_MouseDown(sender As Object, e As MouseEventArgs) Handles File1.MouseDown
' Create a StringCollection to hold the paths of the files you want to drag.
Dim filePaths As New System.Collections.Specialized.StringCollection

' Add the full, qualified paths of the files to the collection.
' This example uses a single file for brevity; you can add multiple paths here.
For Each Item As String In File1.SelectedItems
Try
filePaths.Add(Path.TREE2 + "" + Item.ToString)
Catch ex As Exception
Continue For
End Try
Next

'filePaths.Add(Path.Combine(Application.StartupPath, "TestData1.txt"))
'filePaths.Add(Path.Combine(Application.StartupPath, "TestData2.txt"))
' ... add all other file paths ...

' Create a DataObject and set the FileDrop list.
Dim data As New DataObject()
data.SetFileDropList(filePaths)

' Initiate the drag-and-drop operation, allowing "Copy" or "All" effects.
' Using DragDropEffects.Copy is standard for file drag-and-drop between apps.
File1.DoDragDrop(data, DragDropEffects.Copy)
End Sub
===========

Imports System.IO
Imports System.Windows.Forms

Public Class Form1
Private originalSelection As List(Of Integer)

Public Sub New()
InitializeComponent()

' Example setup
ListBox1.SelectionMode = SelectionMode.MultiExtended
ListBox1.AllowDrop = False ' We are dragging out, not in

' Add some example file paths
ListBox1.Items.Add("C:TempFile1.txt")
ListBox1.Items.Add("C:TempFile2.txt")
ListBox1.Items.Add("C:TempFile3.txt")
End Sub

' Capture selection before mouse down
Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
originalSelection = New List(Of Integer)(ListBox1.SelectedIndices.Cast(Of Integer)())
End Sub


' Start drag without losing selection
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
If e.Button = MouseButtons.Left AndAlso originalSelection IsNot Nothing AndAlso originalSelection.Count > 0 Then
' Restore original selection in case it changed
ListBox1.ClearSelected()
For Each idx In originalSelection
ListBox1.SelectedIndices.Add(idx)
Next

' Prepare file drop list
Dim files As New List(Of String)
For Each idx In originalSelection
Dim path As String = ListBox1.Items(idx).ToString()
If File.Exists(path) Then
files.Add(path)
End If
Next

If files.Count > 0 Then
Dim data As New DataObject(DataFormats.FileDrop, files.ToArray())
ListBox1.DoDragDrop(data, DragDropEffects.Copy)
End If
End If
End Sub
End Class


===========
Compatibility with Third-Party Applications
When dragging between different applications, you must use the standard Windows drag-and-drop formats (like DataFormats.FileDrop). Most third-party applications that support receiving files via drag-and-drop will be listening for this standard format in their own DragEnter and DragDrop event handlers.

The crucial step is creating a DataObject and using SetFileDropList() to ensure the data is provided in a standard, interoperable format.
The third-party application must have its AllowDrop property set to True for the target control to accept drops.
Some older or specific third-party applications might expect different data formats (like a MemoryStream or specific custom formats), but the file path array is the most common and widely supported method.

For more information on programmatically simulating a drop to a third-party application without a user's manual mouse action (which is complex and often requires Windows API calls), refer to resources on programmatic drag-and-drop on Microsoft Learn.


o programmatically drag a file from your VB.NET application and drop it onto a
third-party application, you need to initiate a standard OLE drag-and-drop operation from your VB.NET application.
The third-party application, if built to accept standard Windows file drops (like Windows Explorer or Notepad), will handle the drop automatically.
Step-by-Step Implementation
The key is to create a DataObject containing the file path(s) in the DataFormats.FileDrop format and then call the DoDragDrop method.
1. Set up the UI (e.g., a Button or a ListView)
You'll need a control in your application from which the drag operation will start. A Button or ListView item's MouseDown event is a good place to initiate this.
2. Implement the MouseDown event
In the MouseDown event of your source control, you will:

Specify the full path of the file(s) you want to drag.
Create a DataObject.
Set the data using DataFormats.FileDrop.
Call DoDragDrop to start the operation.

Here is a VB.NET code snippet (for Windows Forms) that initiates a drag operation with a single file:
vb.net

Imports System.IO
Imports System.Collections.Specialized ' Required for StringCollection

Private Sub YourControl_MouseDown(sender As Object, e As MouseEventArgs) Handles YourControl.MouseDown
' Only start the drag if the left mouse button is pressed
If e.Button = Windows.Forms.MouseButtons.Left Then
' Define the path(s) to the file(s) you want to drag.
' Use StringCollection for multiple files, or a String array for one or more.
Dim filePaths As New StringCollection()
' Example: Add a specific file from your application's startup path
Dim filePath As String = Path.Combine(Application.StartupPath, "YourFileName.txt")

' Ensure the file exists before attempting to drag it
If File.Exists(filePath) Then
filePaths.Add(filePath)

' Create a DataObject and set the file drop list
Dim data As New DataObject()
data.SetFileDropList(filePaths)

' Start the drag-and-drop operation, allowing Copy effects
Me.DoDragDrop(data, DragDropEffects.Copy)
Else
MessageBox.Show("File not found: " & filePath)
End If
End If
End Sub


Considerations for Third-Party Applications

Standard Formats: By using DataFormats.FileDrop and a StringCollection of paths, your application adheres to the standard Windows OLE drag-and-drop contract, ensuring compatibility with most third-party applications that support file drops (e.g., Windows Explorer, email clients, specific document management systems).
Permissions (UIPI): Be aware of User Interface Privilege Isolation (UIPI). If your VB.NET application is running with Administrator privileges, it will not be able to drag and drop files into a third-party application running as a standard (non-administrator) user (e.g., dragging from an elevated Visual Studio instance to a normal Windows Explorer window). If this is an issue, run both applications at the same privilege level.
Programmatic Drop (Advanced): If the target application does not support standard drag-and-drop or you need to automate the "drop" part of the process without user interaction (e.g., navigating to a specific folder within the target app first), this becomes significantly more complex, often requiring Windows API calls (SendMessage, WM_DROPFILES) or UI automation tools, which are beyond basic drag-and-drop functionality. The simple DoDragDrop method handles the initiation of the drag, but the target controls the drop



Re: Need help dragging File FROM ListView to Explorer (and other places)
Use the listview mousedown event. If the left button is held down and you have files selected, use

Code:
listviewname.dodragdrop(dataformats.filedrop, new string() {“file1.ext”, etc})
The dataformats and the string array of filenames are the important parts. Windows explorer will recognise your files. All of your previous code was what you’d use to enable dropping in your listview. You might want to keep your listview’s allowdrop property, and handle dragover, so you can see that something is being dragged above your listview. Don’t handle the dragdrop event if you don’t want files dropped in your listview

=================================

Private Sub ListView1_DragDrop1(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListView1.DragDrop

If e.Data.GetDataPresent(DataFormats.FileDrop) Then

Dim MyFiles() As String
Dim i As Integer

' Assign the files to an array.
MyFiles = e.Data.GetData(DataFormats.FileDrop)
' Loop through the array and add the files to the list.
For i = 0 To MyFiles.Length - 1

Dim lvitem As New ListViewItem

lvitem.Text = System.IO.Path.GetFileNameWithoutExtension(MyFiles(i)) 'File Name "Notepad"
lvitem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(MyFiles(i)).Extension) 'Just the extension, soon to be type
lvitem.SubItems.Add(((My.Computer.FileSystem.GetFileInfo(MyFiles(i)).Length) / 1000) & " KB") 'File Size e.g. "2,400KB"
lvitem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(MyFiles(i)).DirectoryName) 'Path
ListView1.Items.Add(lvitem)

Next
End If

End Sub

3rd party


To programmatically simulate a drag-and-drop operation in VB.NET, where files are dropped into a third-party application, you can use the DoDragDrop method in combination with the Windows API for more advanced scenarios. Below is an example of how you can achieve this:

Example: Drag and Drop Files to a Third-Party Application

Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Class DragDropHelper


Private Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr
End Function


Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr
End Function

Private Const WM_DROPFILES As Integer = &H233

Public Shared Sub DragAndDropFile(filePath As String, targetWindowTitle As String)
' Find the target window by its title
Dim targetWindowHandle As IntPtr = FindWindow(Nothing, targetWindowTitle)

If targetWindowHandle = IntPtr.Zero Then
MessageBox.Show("Target application window not found.")
Return
End If

' Create a DataObject containing the file path
Dim dataObject As New DataObject(DataFormats.FileDrop, New String() {filePath})

' Simulate the drag-and-drop operation
Clipboard.SetDataObject(dataObject, True)
SendMessage(targetWindowHandle, WM_DROPFILES, IntPtr.Zero, IntPtr.Zero)
End Sub

End Class

Another example using file explorer


Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
Dim data As New DataObject()
Dim filePaths As New StringCollection

filePaths.Add(Path.Combine(Application.StartupPath, "TestData.txt"))
data.SetFileDropList(filePaths)
DoDragDrop(data, DragDropEffects.Copy)
End Sub
Vb.net



1
01/03/2026
Vb.net Formatting Replacing Text In A String
replace trim
Replacing
Dim APOS2 As Integer, APOS As Integer
A = Replace(A, Chr(9), " ")
APOS2 = Len(A) : APOS = Len(LTrim$(A)) : APOS = APOS2 - APOS
A = Trim$(A)
A = Replace(A, Chr(34), Chr(34) + "+chr(34)+" + Chr(34))
Vb.net



0
01/13/2025
Vb.net Formatting Sort Files By Date
delete sort listbox list box date files selected
Webtools File Management

Remove unwanted items

always LOOP BACKWARDS
' Define the unwanted text
Dim unwantedText As String = "Unwanted Item Text"

' Loop backwards from the last item to the first (ListBox.Items is 0-based)
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
' Check if the current item matches the unwanted text
If ListBox1.Items(i).ToString() = unwantedText Then
' If it matches, remove the item at the current index
ListBox1.Items.RemoveAt(i)
End If
Next
'PRINT CONTENT TO VIEW
DIM B AS string
For i As Integer = 0 to ListBox1.Items.Count - 1
B=B + ListBox1.Items(i).ToString()+VBCRLF

Next
table.text=B


'PRINT SELECTED CONTENT TO VIEW
If ListBox1.SelectedItems.Count > 0 Then
MessageBox.Show("Processing " & ListBox1.SelectedItems.Count.ToString() & " items.")

' Loop through each selected item in the collection
For Each selectedItem As Object In ListBox1.SelectedItems
' You can cast the item to a specific type if needed (e.g., String)
Dim itemText As String = selectedItem.ToString()

' Perform your processing logic here
Debug.WriteLine("Processing item: " & itemText)
' Example: add to another listbox
' ListBox2.Items.Add(itemText)
Next

' Optional: Clear the selection after processing
' ListBox1.ClearSelected()
Else
MessageBox.Show("No items selected.")
End If



webtools
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btDateSort.Click
Dim J As Integer, N As Integer = 0, N2 As Integer = 0
Dim DateFile As Array = Directory.GetFiles(Path.TREE2).OrderBy(Function(d) New FileInfo(d).CreationTime).ToArray
File1.Items.Clear()
N = DateFile(J).LastIndexOf("")
For J = 0 To DateFile.Length - 1
N2 = DateFile(J).length - N - 1
File1.Items.Add(DateFile(J).substring(N + 1, N2))
Next
End Sub

StrFilesArray=Directory.GetFiles(DirectoryPath).OrderBy(Function(d) New FileInfo(d).CreationTime).ToArray

Dim name As String
Dim list As List(of DateTime) = new List(of DateTime)
For Each file As String In System.IO.Directory.GetFiles(directoryPath)
name = System.IO.Path.GetFileNameWithoutExtension(file)
list.Add(Datetime.ParseExact(name, "dd-MM-yyyy", CultureInfo.InvariantCulture))
Next
list.Sort(New Comparison(Of Date)(Function(x As Date, y As Date) y.CompareTo(x)))
ComboBox1.DataSource = list
Vb.net



3
01/25/2026
Vb.net Function Populating The Treeview List
treeview files directory
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateTreeView(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
End Sub

Private Sub PopulateTreeView(path As String)
' Clear the TreeView control
TreeView1.Nodes.Clear()

' Create the root node for the TreeView
Dim rootNode = New TreeNode(path) With {.Tag = path}
TreeView1.Nodes.Add(rootNode)

' Recursively add child nodes for directories and their files
AddDirectories(rootNode)
End Sub

Private Sub AddDirectories(parentNode As TreeNode)
' Get the path of the parent node
Dim path = DirectCast(parentNode.Tag, String)

' Get the directories in the current path
Dim directories = IO.Directory.GetDirectories(path)

' Add child nodes for each directory
For Each dir As String In directories
Dim directoryNode = New TreeNode(IO.Path.GetFileName(dir)) With {.Tag = dir}
parentNode.Nodes.Add(directoryNode)

Try
' Get the files in the current directory
Dim files = IO.Directory.GetFiles(dir)

' Add child nodes for each file
For Each file In files
Dim fileNode = New TreeNode(IO.Path.GetFileName(file)) With {.Tag = file}
directoryNode.Nodes.Add(fileNode)
Next

' Recursively add child nodes for subdirectories
AddDirectories(directoryNode)
Catch invalidAccessEx As UnauthorizedAccessException
directoryNode.ForeColor = Color.Red
End Try
Next
End Sub
Vb.net



1
12/27/2023
Vb.net Function Outlook Email
outlook move email
OUTLOOK
Vb.net



4
07/21/2025
Vb.net Function Calling A Click Event
call
Vb.net Events
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button2_Click(Sender, e)
End Sub

BTbulkMove_Click(sender As Object, e As EventArgs) translates to BTbulkMove_Click(sender, e)

BTtest_Click(sender As Object, e As EventArgs) translates to BTtest_Click(sender, e)
Vb.net



0
08/21/2025
Vb.net Function Function Variable Passing
function
Function
Key Points:
ByVal passes a copy of the variable.
Changes inside the function do not modify the original variable.
This is the default passing mechanism in VB.NET if you don’t specify ByRef.

When to use ByVal

When you want to protect the original variable from being changed.
When passing immutable data (e.g., numbers, strings) where modification is unnecessary.
If you want, I can also show you the ByRef version so you can compare how it changes the original variable

Function EmailCriteria(ByRef email_count As Int16)
Dim MV(200, 2) As String, L As Integer
Try
Dim sqL As String = "SELECT [move_to],[subject_filter],[archive] FROM [move_email] WHERE [archive]>0 ORDER BY [move_to],[subject_filter]"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
LAerrorMessage.Text = "error BTbulkMove DB:" & ex.Message
End Try
Do While dr.Read
MV(L, 0) = dr(0) : MV(L, 1) = dr(1) : MV(L, 2) = dr(2)
L = L + 1
Loop
email_count = L - 1
Return MV
End Function
Vb.net



0
02/28/2026
Vb.net Ini Read And Write From Ini File
ini windows API api
Vb.net



3
11/17/2025
Vb.net Keyboard Clipboard
clipboard html text
Vb.net



1205
08/05/2024
Vb.net Language Split Variable Into Array
explode split
Vb.net



2
09/09/2023
Vb.net Language Using Try To Catch Errors
try errors
Mail
Vb.net



0
01/01/2024
Vb.net Setup How To: Change The Default Location For Projects
Default Location Projects folder
How to: Change the Default Location for Projects
Visual Studio 2010
Other Versions
13 out of 21 rated this helpful - Rate this topic

You can change the path where new projects and files are created by using the Options dialog box. Your existing projects remain in their current location. Web-related projects, such as XML Web services and ASP.NET Web applications, are not affected by this setting. The default Web server is based on the most recently used server.
To change the default save location

On the Tools menu, select Options.

From the Projects and Solutions folder, select General.

In the Visual Studio projects location text box, enter a location for files and projects.
Vb.net



1850
09/09/2023
Vb.net Setup Have Application Run In The Background
application background process file explorer

http://www.dreamincode.net/forums/topic/59527-make-a-program-to-run-in-the-background/



This tutorial deals with how to make a standard VB.NET application run
in the background, like a process. By background i mean that the
application will have no interface (form or console) and will run from a
Sub Main(), but will not terminate once all the code in Main has
executed. That means your program will run like a normal form
application, and will only exit when told to. First, create a standard
Windows Form application. Then, go to the solution explorer, and double
click on the item that says My Project.

[attachment=7480:attachment]

Once that is opened, you should see something like this

[attachment=7484:attachment]

There are a few very simple things you need to change there. First,
uncheck the box that says "Enable Application Framework". Then, go to
the box that says "Startup Object:" and change that to Sub Main. Then,
delete the form that was put in your application automatically. By now,
you should notice that there is no startup object in your application.
In fact, there is no Code in your application. So, you need to add a Sub Main in. Add a new module to your application (call it anything you want). Then, add this sub into your module:

1Sub Main()
2 'This will execute when your application
3 'starts up. This is the equivilent of a
4 'Form_Load event in a form application.
5 'Put whatever code you want in this sub,
6 'but make sure you end it with this statement:
7 Application.Run()
8End Sub


Let me explain exactly what this is doing. When you changed the startup
object to Sub Main, you application will execute from a Main routine,
like a console application, so what is stopping it from showing a
console window? Notice the box that says "Application Type:". You will
see that that is set to "Windows Form Application". When you create a
console application, that box is set to "Console Application". When you
create any windows form application, there, of course, is no console
window. That is because the application has a type of "Windows Form
Application", which basically means your application will not show a
console. Of course, in Consle Applications, there are no forms. So what
happens when you application's type is Windows Form Application, and
there is no form in it? Your program will have no interface at all. But,
even though your application is called a Windows Form Application, it
will still exit once all the code in Sub Main has executed, like a
console application. To prevent that, you must have a line at the end of your Main routine that says Application.Run().
That line will prevent your application from closing right after Main
has finished. Now, it will run like a standard form application, just
with no form, and the only way you can close it is with an Application.Exit()
call. And it's as simple as that. You can treat the module your main
routine is in as if it was the code for your form. The only difference
is, there is no form, and you can't add controls to it in the designer
(because there is no interface there to design). So, for example, if you
wanted to add a timer to your application, you can't just drag-and-drop
it on the form, you have to get down and dirty and add it in manually,
with something like this

1Friend WithEvents Timer1 As New Timer()


That will create a timer object, exactly as if it was created by the
designer. To add a tick event handler for it, go to the box near the
top-left of the code editor. Select the item that says "Timer1", or
whatever you called your timer. Then, select the box next to it and it
will show a list of events for that control. Click the one you want,
Tick in this case, and it will add an event handler for that event
directly into your code.

Private Sub laPath_DoubleClick(sender As Object, e As EventArgs) Handles laPath.DoubleClick
Dim filePath As String = laPath.Text 'Example file
Process.Start("explorer.exe", "/select," & filePath) : Application.DoEvents()
End Sub
Vb.net



1215
09/09/2023
Vb.net Setup Compiling Error Locations
errors optimization
Locating Bug Fixes
optimize error
Project- project properties (located towards bottom)
Compile -towards bottom "Advanced Compile Options" uncheck "Enable Optimizations"

============

Resolving the 'Microsoft.Jet.OLEDB.4.0' Provider Not Registered Er…
1
2
3
The error Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine typically occurs when you try to use the Microsoft Jet OLEDB 4.0 driver on a 64-bit operating system. This driver is not compatible with 64-bit systems, leading to this error.

Example

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// Perform database operations
}
Solution 1: Change Project Build Configuration

One common solution is to change the build configuration of your project to target x86 (32-bit) instead of Any CPU or x64.

Steps:

Open your project in Visual Studio.

Go to Project Properties > Build.

Change the Platform target to x86.

Rebuild your project.

Solution 2: Use Microsoft.ACE.OLEDB.12.0

Another solution is to use the Microsoft Access Database Engine, which provides a 64-bit compatible driver.

Example:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabase.accdb;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// Perform database operations
}
Solution 3: Enable 32-bit Applications in IIS

If you are running a web application, you can enable 32-bit applications in IIS
3
.

Steps:

Open IIS Manager.

Select the application pool your application is using.

Click on Advanced Settings.

Set Enable 32-Bit Applications to True.

By following these steps, you can resolve the Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine error and ensure your application runs smoothly on both 32-bit and 64-bit systems.

Learn more:
1 -
stackoverflow.com
2 -
answers.microsoft.com
3 -
stackoverflow.com




Resolving the 'Microsoft.Jet.OLEDB.4.0' Provider Not Registered Er…
1
2
3
The error Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine typically occurs when you try to use the Microsoft Jet OLEDB 4.0 driver on a 64-bit operating system. This driver is not compatible with 64-bit systems, leading to this error.

Example

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// Perform database operations
}
Solution 1: Change Project Build Configuration

One common solution is to change the build configuration of your project to target x86 (32-bit) instead of Any CPU or x64.

Steps:

Open your project in Visual Studio.

Go to Project Properties > Build.

Change the Platform target to x86.

Rebuild your project.

Solution 2: Use Microsoft.ACE.OLEDB.12.0

Another solution is to use the Microsoft Access Database Engine, which provides a 64-bit compatible driver.

Example:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabase.accdb;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// Perform database operations
}
Solution 3: Enable 32-bit Applications in IIS

If you are running a web application, you can enable 32-bit applications in IIS
3
.

Steps:

Open IIS Manager.

Select the application pool your application is using.

Click on Advanced Settings.

Set Enable 32-Bit Applications to True.

By following these steps, you can resolve the Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine error and ensure your application runs smoothly on both 32-bit and 64-bit systems.

Learn more:
1 -
stackoverflow.com
2 -
answers.microsoft.com
3 -
stackoverflow.com
Vb.net



0
07/23/2025
Vb.net String String Functions
substring
[CHAR]
'// see indexof also
Dim myString As String = "ABCDE"
Dim myChar As Char
myChar = myString.Chars(3) '//myChar = "D"

[CONCAT]
Dim aString As String = "A"
Dim bString As String = "B"
Dim cString As String = "C"
Dim dString As String = "D"
Dim myString As String
' myString = "ABCD"
myString = String.Concat(aString, bString, cString, dString)


[INDEXOF]
'// see char also
Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3

[instr]
[left]

[LENGTH]
Dim MyString As String = "This is my string"
Dim stringLength As Integer
' Explicitly set the string to Nothing.
MyString = Nothing
' stringLength = 0
stringLength = Len(MyString)
' This line, however, causes an exception to be thrown.
stringLength = MyString.Length

[MID]
'//see substring. first charcter is position 1
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 3)


[right]

[SPLIT]
'// returns an array
Dim shoppingList As String = "Milk,Eggs,Bread"
Dim shoppingItem(2) As String
shoppingItem = shoppingList.Split(","c)



[SUBSTRING]
'//first character is position zero. See mid()
Dim aString As String = "A String"
Dim bString As String
bString = aString.SubString(2,6) '//bString = "String"
or
Dim aString As String = "Left Center Right"
Dim subString As String
' subString = "Center"
subString = aString.SubString(5,6)



Visual Basic .NET methods are used as inherent functions of the language. They may be used without qualification in your code. The following example shows typical use of a Visual Basic .NET string-manipulation command:

In this example, the Mid function performs a direct operation on aString and assigns the value to bString.

You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods and instance methods.

A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example:

Dim aString As String
bString = String.Copy("A literal string")

In the preceding example, the String.Copy method is a static method, which acts upon an expression it is given and assigns the resulting value to bString.

NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing.
Comparing Strings

You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class. In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used:

Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare (myString, secondString)

This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than a null reference.

Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into account, and to compare substrings within the supplied strings. For more information on how to compare strings, see String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method.
Searching for Strings Within Your Strings

There are times when it is useful to have data about the characters in your string and the positions of those characters within your string. A string can be thought of as an array of characters (Char instances); you can retrieve a particular character by referencing the index of that character through the Chars property. For example:


You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following example:

Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3

In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can also use the String.LastIndexOf Method to search for the last occurrence of a character in your string.
Creating New Strings from Old

When using strings, you may want to modify your strings and create new ones. You may want to do something as simple as convert the entire string to uppercase, or trim off trailing spaces; or you may want to do something more complex, such as extracting a substring from your string. The System.String class provides a wide range of options for modifying, manipulating, and making new strings out of your old ones.

To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows:


You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below:

Dim myString As String = "UpPeR oR LoWeR cAsE"
Dim newString As String
' newString = "UPPER OR LOWER CASE"
newString = UCase(myString)
' newString = "upper or lower case"
newString = LCase(myString)
' newString = "UPPER OR LOWER CASE"
newString = myString.ToUpper
' newString = "upper or lower case"
newString = myString.ToLower

The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a given string. For information on these commands, see Format Function or String.Format Method.

You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the Visual Basic .NET Trim function. An example is shown:

Dim spaceString As String = _
" This string will have the spaces removed "
Dim oneString As String
Dim twoString As String
' This removes all trailing and leading spaces.
oneString = spaceString.Trim
' This also removes all trailing and leading spaces.
twoString = Trim(spaceString)

If you only want to remove trailing spaces, you can use the String.TrimEnd Method or the RTrim function, and for leading spaces you can use the String.TrimStart Method or the LTrim function. For more details, see LTrim, RTrim, and Trim Functions functions.

The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your string. The following example trims all leading and trailing instances of the "#" character:

Dim myString As String = "#####Remove those!######"
Dim oneString As String
OneString = myString.Trim("#")

You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method.

If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can replace them with another character using the String.Replace Method. For example:

Dim aString As String = "This is My Str@o@o@ing"
Dim myString As String
Dim anotherString As String
' myString = "This is My String"
myString = aString.Remove(14, 5)
' anotherString = "This is Another String"
anotherString = myString.Replace("My", "Another")

You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid Statement can also be used to replace an interior string with another string.

You can also use the String.Insert Method to insert a string within another string, as in the following example:

Dim aString As String = "This is My Stng"
Dim myString As String
' Results in a value of "This is My String".
myString = aString.Insert(13, "ri")

The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the second parameter is the string to be inserted.

You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example:

Dim shoppingItem(2) As String
Dim shoppingList As String
shoppingItem(0) = "Milk"
shoppingItem(1) = "Eggs"
shoppingItem(2) = "Bread"
shoppingList = String.Join(",", shoppingItem)

The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the method still adds a separator string between all the empty instances in your array.

You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c.

The Visual Basic .NET Mid Function can be used to generate substrings of your string. The following example shows this functions in use:

Dim aString As String = "Left Center Right"
Dim rString, lString, mString As String
' rString = "Right"
rString = Mid(aString, 13)
' lString = "Left"
lString = Mid(aString, 1, 4)
' mString = "Center"
mString = Mid(aString, 6,6)

Substrings of your string can also be generated using the String.Substring Method. This method takes two arguments: the character index where the substring is to start, and the length of the substring. The String.Substring method operates much like the Mid function. An example is shown below:


There is one very important difference between the String.SubString method and the Mid function. The Mid function takes an argument that indicates the character position for the substring to start, starting with position 1. The String.SubString method takes an index of the character in the string at which the substring is to start, starting with position 0. Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use with the Mid function, but 0,1,2,3,4 for use with the System.String function.
Vb.net



1054
09/09/2023
Vb.net String Array Manipulation
count split explode
[Return number of element in array]
dotg.count= items in array

[Split a patterned string into separate elements like a csv file]
myfile="dog,10,cat,40,fish,50"
dotg=split(myfile,",")
Vb.net



1039
09/09/2023
Vb.net String Some Good String Functions
concat length mid
[CHAR]
'// see indexof also
Dim myString As String = "ABCDE"
Dim myChar As Char
myChar = myString.Chars(3) '//myChar = "D"

[CONCAT]
Dim aString As String = "A"
Dim bString As String = "B"
Dim cString As String = "C"
Dim dString As String = "D"
Dim myString As String
' myString = "ABCD"
myString = String.Concat(aString, bString, cString, dString)


[INDEXOF]
'// see char also
Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3

[instr]

[left]

[LENGTH]
Dim MyString As String = "This is my string"
Dim stringLength As Integer
' Explicitly set the string to Nothing.
MyString = Nothing
' stringLength = 0
stringLength = Len(MyString)
' This line, however, causes an exception to be thrown.
stringLength = MyString.Length

[MID]
'//see substring. first charcter is position 1
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 3)


[right]

[SPLIT]
'// returns an array
Dim shoppingList As String = "Milk,Eggs,Bread"
Dim shoppingItem(2) As String
shoppingItem = shoppingList.Split(","c)



[SUBSTRING]
'//first character is position zero. See mid()
Dim aString As String = "A String"
Dim bString As String
bString = aString.SubString(2,6) '//bString = "String"
or
Dim aString As String = "Left Center Right"
Dim subString As String
' subString = "Center"
subString = aString.SubString(5,6)



Visual Basic .NET methods are used as inherent functions of the language. They may be used without qualification in your code. The following example shows typical use of a Visual Basic .NET string-manipulation command:

In this example, the Mid function performs a direct operation on aString and assigns the value to bString.

You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods and instance methods.

A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example:

Dim aString As String
bString = String.Copy("A literal string")

In the preceding example, the String.Copy method is a static method, which acts upon an expression it is given and assigns the resulting value to bString.

NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing.
Comparing Strings

You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class. In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used:

Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare (myString, secondString)

This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than a null reference.

Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into account, and to compare substrings within the supplied strings. For more information on how to compare strings, see String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method.
Searching for Strings Within Your Strings

There are times when it is useful to have data about the characters in your string and the positions of those characters within your string. A string can be thought of as an array of characters (Char instances); you can retrieve a particular character by referencing the index of that character through the Chars property. For example:


You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following example:

Dim myString As String = "ABCDE"
Dim myInteger As Integer
myInteger = myString.IndexOf("D") ' myInteger = 3

In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can also use the String.LastIndexOf Method to search for the last occurrence of a character in your string.
Creating New Strings from Old

When using strings, you may want to modify your strings and create new ones. You may want to do something as simple as convert the entire string to uppercase, or trim off trailing spaces; or you may want to do something more complex, such as extracting a substring from your string. The System.String class provides a wide range of options for modifying, manipulating, and making new strings out of your old ones.

To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows:


You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below:

Dim myString As String = "UpPeR oR LoWeR cAsE"
Dim newString As String
' newString = "UPPER OR LOWER CASE"
newString = UCase(myString)
' newString = "upper or lower case"
newString = LCase(myString)
' newString = "UPPER OR LOWER CASE"
newString = myString.ToUpper
' newString = "upper or lower case"
newString = myString.ToLower

The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a given string. For information on these commands, see Format Function or String.Format Method.

You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the Visual Basic .NET Trim function. An example is shown:

Dim spaceString As String = _
" This string will have the spaces removed "
Dim oneString As String
Dim twoString As String
' This removes all trailing and leading spaces.
oneString = spaceString.Trim
' This also removes all trailing and leading spaces.
twoString = Trim(spaceString)

If you only want to remove trailing spaces, you can use the String.TrimEnd Method or the RTrim function, and for leading spaces you can use the String.TrimStart Method or the LTrim function. For more details, see LTrim, RTrim, and Trim Functions functions.

The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your string. The following example trims all leading and trailing instances of the "#" character:

Dim myString As String = "#####Remove those!######"
Dim oneString As String
OneString = myString.Trim("#")

You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method.

If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can replace them with another character using the String.Replace Method. For example:

Dim aString As String = "This is My Str@o@o@ing"
Dim myString As String
Dim anotherString As String
' myString = "This is My String"
myString = aString.Remove(14, 5)
' anotherString = "This is Another String"
anotherString = myString.Replace("My", "Another")

You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid Statement can also be used to replace an interior string with another string.

You can also use the String.Insert Method to insert a string within another string, as in the following example:

Dim aString As String = "This is My Stng"
Dim myString As String
' Results in a value of "This is My String".
myString = aString.Insert(13, "ri")

The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the second parameter is the string to be inserted.

You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example:

Dim shoppingItem(2) As String
Dim shoppingList As String
shoppingItem(0) = "Milk"
shoppingItem(1) = "Eggs"
shoppingItem(2) = "Bread"
shoppingList = String.Join(",", shoppingItem)

The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the method still adds a separator string between all the empty instances in your array.

You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c.

The Visual Basic .NET Mid Function can be used to generate substrings of your string. The following example shows this functions in use:

Dim aString As String = "Left Center Right"
Dim rString, lString, mString As String
' rString = "Right"
rString = Mid(aString, 13)
' lString = "Left"
lString = Mid(aString, 1, 4)
' mString = "Center"
mString = Mid(aString, 6,6)

Substrings of your string can also be generated using the String.Substring Method. This method takes two arguments: the character index where the substring is to start, and the length of the substring. The String.Substring method operates much like the Mid function. An example is shown below:


There is one very important difference between the String.SubString method and the Mid function. The Mid function takes an argument that indicates the character position for the substring to start, starting with position 1. The String.SubString method takes an index of the character in the string at which the substring is to start, starting with position 0. Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use with the Mid function, but 0,1,2,3,4 for use with the System.String function.
Vb.net



1036
09/09/2023
Vb.net Variables Create New Arrays
array null
Read through entire array
For Each fruit As String In MV
Console.WriteLine(fruit)
Next

max number of elements array.length
For L = 0 To MV.GetUpperBound(0) elements stored



Either

Dim strings = New String() {"a", "b", "c"}
or

Dim strings() As String = {"a", "b", "c"}
or strings() As String = {}
should work
Vb.net



2
09/09/2023

Software Web Design