How to Code 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 | ABCDEFGHIJKLMNOPQRSTUVWXYZONPRTOFF codeid operationid title keywords application code languageid show_html show_iframe make_public viewed viewed_date language operation <- Look Inside DataConditions:Order: 1|2|3|4|5|6|7|8|50 Language Operation Title Keywords Application Code Languageid Show Html Show Iframe Make Public Viewed Viewed Date Vb.net Customizing Running A 3rd Party Application getini 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. ''' Example 1 Private Sub OpenMicrosoftWord(ByVal f As String) Dim startInfo As New ProcessStartInfo startInfo.FileName = "WINWORD.EXE" startInfo.Arguments = f Process.Start(startInfo) End Sub Example 2 Private Sub FoldersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FoldersToolStripMenuItem.Click Dim B As String = PathSWD.TREE If Dir(B + "savedfolders.txt") <> "" Then Dim startInfo As New ProcessStartInfo startInfo.FileName = "notepad.exe" startInfo.Arguments = B + "savedfolders.txt" Process.Start(startInfo) End If Application.DoEvents() End Sub Old School Example 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 6 05/05/2026 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 3 05/05/2026 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 2 05/05/2026 Vb.net Customizing Handling Directories directory current Developer Application.StartupPath Creating Directories If Not System.IO.Directory.Exists(YourPath) Then System.IO.Directory.CreateDirectory(YourPath) End If Vb.net 2 05/05/2026 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 5 05/05/2026 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 2 05/05/2026 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 3 05/05/2026 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 3 05/05/2026 Vb.net Customizing Keeping Harddrive Awake awake external hard drive Web Tools WORKS ON EXTERNAL DRIVES To prevent an external hard drive from sleeping using VB.NET, create a background thread that writes a tiny, hidden text file to the drive every 60–120 seconds. This activity keeps the drive active, preventing it from entering a low-power sleep state, which is generally more effective than relying on OS power settings . Imports System.IO Imports System.Threading Module Module1 ' Set the path to your external drive Const DrivePath As String = "E:" Const FileName As String = "keepalive.txt" Sub Main() Console.WriteLine("Preventing drive " & DrivePath & " from sleeping...") Dim keepAliveThread As New Thread(AddressOf KeepDriveAwake) keepAliveThread.IsBackground = True keepAliveThread.Start() ' Keep the console app running Console.ReadLine() End Sub Sub KeepDriveAwake() Dim filePath As String = Path.Combine(DrivePath, FileName) Do Try ' Write a timestamp to the file File.WriteAllText(filePath, DateTime.Now.ToString()) ' Set file to hidden so it's not distracting File.SetAttributes(filePath, FileAttributes.Hidden) Console.WriteLine("Ping: " & DateTime.Now.ToString()) Catch ex As Exception Console.WriteLine("Error: " & ex.Message) End Try ' Wait 90 seconds before writing again Thread.Sleep(90000) Loop End Sub End Module Key Considerations Drive Letter: Ensure DrivePath (e.g., "E:") matches your external drive letter. Interval: A 60–90 second interval (90000 milliseconds) is usually sufficient to prevent sleep without causing excessive wear. Alternatives: You can also disable "Allow the computer to turn off this device" in Device Manager for the USB root hub, notes this YouTube video. Example from webtools Private Sub FoldersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FoldersToolStripMenuItem.Click If PathSWD.DriveAlive = True Then PathSWD.DriveAlive = False : MsgBox("Drive alive is turned off") : Exit Sub Else PathSWD.DrivePath = GetIni(My.Computer.Name, "DrivePath", INI) If PathSWD.DrivePath = "" Then MsgBox("Enter 'DrivePath=' value in INI file") : Exit Sub End If PathSWD.FileName = GetIni(My.Computer.Name, "FileName", INI) If PathSWD.FileName = "" Then MsgBox("Enter 'FileName=' value in INI file") : Exit Sub End If Dim cdrive As System.IO.DriveInfo cdrive = My.Computer.FileSystem.GetDriveInfo(PathSWD.DrivePath) If cdrive.IsReady = False Then MsgBox("This " + PathSWD.DrivePath + " drive is NOT READY.") : Exit Sub End If PathSWD.DriveAlive = True : MsgBox("Drive alive is turned on") End If Dim keepAliveThread As New Thread(AddressOf KeepDriveAwake) keepAliveThread.IsBackground = True keepAliveThread.Start() End Sub Public Sub KeepDriveAwake() Dim filePath As String = Path.Combine(PathSWD.DrivePath, PathSWD.FileName) Do Try ' Write a timestamp to the file File.WriteAllText(filePath, DateTime.Now.ToString()) ' Set file to hidden so it's not distracting File.SetAttributes(filePath, FileAttributes.Hidden) Console.WriteLine("Ping: " & DateTime.Now.ToString()) Catch ex As Exception 'Console.WriteLine("Error: " & ex.Message) MsgBox("driveawake error") End Try ' Wait 180 seconds before writing again Thread.Sleep(180000) 'MsgBox("Write " + filePath) Loop Until PathSWD.DriveAlive = False End Sub WORKS ON COMPUTER ONLY Imports System.Runtime.InteropServices Public Class PowerManagement Private Shared Function SetThreadExecutionState(esFlags As EXECUTION_STATE) As EXECUTION_STATE End Function Private Enum EXECUTION_STATE As UInteger ES_SYSTEM_REQUIRED = &H1 ES_CONTINUOUS = &H80000000UI End Enum ' Keeps the system awake Public Shared Sub KeepAlive() SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS) End Sub ' Resets to default power behavior Public Shared Sub AllowSleep() SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS) End Sub End Class Vb.net 6 05/05/2026 Vb.net Customizing Rem Out Code rem Developer Comment multiple lines: Ctrl + K, then Ctrl + C Uncomment them: Ctrl + K, then Ctrl + U Here are the correct, verified ways to “REM out” (comment out) multiple lines in VB.NET, based strictly on real Visual Basic language rules and Visual Studio behavior. VB.NET does not have a native multi?line comment block like /* */ in C# or Java. This is confirmed in the official REM documentation: each comment must begin its own line, because comments cannot span multiple lines automatically 1 4. However, you can comment out multiple lines using any of the following real methods: 1. Add ' or REM to every line (language rule) VB.NET allows single?line comments using: The apostrophe ' The keyword REM (requires a space) Both apply only to the current line, so you repeat them for each line 1 4. Example: Vb' First commented line ' Second commented line ' Third commented line or: VbREM First commented line REM Second commented line REM Third commented line 2. Use Visual Studio shortcut: Ctrl+K, Ctrl+C (comment) Visual Studio lets you “comment out” multiple lines at once, even though VB.NET itself does not support block comments. This is done with the keyboard shortcut 2 3 5: Comment multiple lines: Ctrl + K, then Ctrl + C Uncomment them: Ctrl + K, then Ctrl + U Visual Studio’s multiple?line comment shortcut (Ctrl+K, Ctrl+C) #If False Then … #End If to disable a block of code 3. Use #If False Then … #End If (compiler?ignored block) This is not technically a comment, but it is a valid and common VB.NET technique for disabling multiple lines at once. Example 5: Vb#If False Then Dim x As Integer x = 10 Console.WriteLine(x) #End If Because the condition is False, the compiler ignores the entire block—effectively acting like a multi?line comment. Summary VB.NET does not support multi?line comments, but you can “REM out” multiple lines using: ' or REM on each line (language standard) Visual Studio’s multiple?line comment shortcut (Ctrl+K, Ctrl+C) #If False Then … #End If to disable a block of code If you'd like, I can generate a Visual Studio macro, extension, or tool to automate REM?style commenting across many lines. 1-Microsoft.com 2-Stackoverflow.com 3-Codegenes.net 4-Github.com 5-Umatechnology.org Vb.net 0 05/21/2026 Vb.net Database Create Read Only Recordset create recordset error list box LISTBOX Imports System.Data.Oledb Solution Beta1 'Grabs data from a table and posts it into a ListView Dim Table_ As String = "mulitreplace ORDER BY title" Dim query As String = "SELECT * FROM " & Table_ Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=webtools1.mdb;" Dim ds As New DataSet Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_) cnn.Open() Dim cmd As New OleDbCommand(query, cnn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) cnn.Close() Dim t1 As DataTable = ds.Tables(Table_) txMultiAction.Items.Clear() txMultiAction.ValueMember = "replaceid" txMultiAction.DisplayMember = "title" txMultiAction.DataSource = 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) 'MsgBox(Item(1)) 'Dim NextListItem As New ListViewItem(Item) 'ListView1.Items.Add(NextListItem) Next 'end Beta Dim con As New OledbConnection("Provider=microsoft.Jet.oledb.4.0DataSource=D:mydata.mdb;") Dim cmd As New OledbCommand Public var1 As String Public Sub New() con.Open() cmd.Connection = con cmd.CommandText = "SELECT * FROM table1" End Sub Public Sub creates() cmd.CommandText = "INSERT INTO table1(Neyms) VALUES('" + var1 + "')" cmd.ExecuteNonQuery() End Sub Permalink Posted 16-Jan-13 22:39pm vinodkumarnie Solution 2 Grabs data from a table and posts it into a ListView Dim Table_ As String = "Table1" Dim query As String = "SELECT * FROM " & Table_ Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TestDatabase.mdb;" Dim ds As New DataSet Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_) cnn.Open() Dim cmd As New OleDbCommand(query, cnn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) cnn.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) Dim NextListItem As New ListViewItem(Item) ListView1.Items.Add(NextListItem) Next Vb.net 4 05/05/2026 Vb.net Database Delete A Record From A DAO Recordset delete recordset Sub DeleteDuplicateShippers() Dim dbsNorthwind As DAO.Database Dim rstShippers As DAO.Recordset Dim strSQL As String Dim strName As String On Error GoTo ErrorHandler Set dbsNorthwind = CurrentDb strSQL = "SELECT * FROM Shippers ORDER BY CompanyName, ShipperID" Set rstShippers = dbsNorthwind.OpenRecordset(strSQL, dbOpenDynaset) ' If no records in Shippers table, exit. If rstShippers.EOF Then Exit Sub strName = rstShippers![CompanyName] rstShippers.MoveNext Do Until rstShippers.EOF If rstShippers![CompanyName] = strName Then rstShippers.Delete Else strName = rstShippers![CompanyName] End If rstShippers.MoveNext Loop Exit Sub ErrorHandler: MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description End Function Vb.net 2 05/05/2026 Vb.net Database Extract Data From A Record In A DAO Recordset extreact recordset After you have located a particular record or records, you may want to extract data to use in your application instead of modifying the underlying source table. Copy a single field You can copy a single field of a record to a variable of the appropriate data type. The following example extracts three fields from the first record in a Recordset object. VB Copy Dim dbsNorthwind As DAO.Database Dim rstEmployees As DAO.Recordset Dim strFirstName As String Dim strLastName As String Dim strTitle As String Set dbsNorthwind = CurrentDb Set rstEmployees = dbsNorthwind.OpenRecordset("Employees") rstEmployees.MoveFirst strFirstName = rstEmployees!FirstName strLastName = rstEmployees!LastName strTitle = rstEmployees!Title Copy entire records to an array To copy one or more records, you can create a two-dimensional array and copy records one at a time. You increment the first subscript for each field and the second subscript for each record. A fast way to do this is to use the GetRows method, which returns a two-dimensional array. The first subscript identifies the field and the second identifies the row number, as follows. VB Copy varRecords(intField, intRecord) The following code example uses an SQL statement to retrieve three fields from a table called Employees into a Recordset object. It then uses the GetRows method to retrieve the first three records of the Recordset, and it stores the selected records in a two-dimensional array. It then prints each record, one field at a time, by using the two array indexes to select specific fields and records. To show how the array indexes are used, the following example uses a separate statement to identify and print each field of each record. In practice, it would be more reliable to use two loops, one nested in the other, and to provide integer variables for the indexes that step through both dimensions of the array. VB Copy Sub GetRowsTest() Dim dbsNorthwind As DAO.Database Dim rstEmployees As DAO.Recordset Dim varRecords As Variant Dim intNumReturned As Integer Dim intNumColumns As Integer Dim intColumn As Integer Dim intRow As Integer Dim strSQL As String On Error GoTo ErrorHandler Set dbsNorthwind = CurrentDb strSQL = "SELECT FirstName, LastName, Title FROM Employees" Set rstEmployees = dbsNorthwind.OpenRecordset(strSQL, dbOpenSnapshot) varRecords = rstEmployees.GetRows(3) intNumReturned = UBound(varRecords, 2) + 1 intNumColumns = UBound(varRecords, 1) + 1 For intRow = 0 To intNumReturned - 1 For intColumn = 0 To intNumColumns - 1 Debug.Print varRecords(intColumn, intRow) Next intColumn Next intRow rstEmployees.Close dbsNorthwind.Close Set rstEmployees = Nothing Set dbsNorthwind = Nothing Exit Sub ErrorHandler: MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description End Sub Use subsequent calls to the GetRows method if more records are available. Because the array is filled as soon as you call the GetRows method, you can see why this approach is much faster than copying one field at a time. Notice also that you don't have to declare the Variant as an array, because this is done automatically when the GetRows method returns records. This enables you to use fixed-length array dimensions without knowing how many records or fields will be returned, instead of using variable-length dimensions that take up more memory. If you are trying to retrieve all the rows by using multiple GetRows calls, use the EOF property to be sure that you are at the end of the Recordset. The GetRows method may return fewer rows than you request. If you request more than the remaining number of rows in a Recordset, for example, the GetRows method returns only the rows that remain. Similarly, if it cannot retrieve a row in the range requested, it does not return that row. For example, if the fifth record cannot be retrieved in a group of 10 records that you are trying to retrieve, the GetRows method returns four records and leaves the current record position on the record that caused a problem, and does not generate a run-time error. This situation may occur if a record in a dynaset was deleted by another user. If it returns fewer records than the number requested and you are not at the end of the file, you need to read each field in the current record to determine what error the GetRows method encountered. Because the GetRows method always returns all the fields in the Recordset object, you may want to create a query that returns just the fields that you need. This is especially important for OLE Object and Memo fields. Vb.net 4 05/05/2026 Vb.net Database Using The Datagridview Control datagrid access mdb datasource view example coding access developer boxes start at H:20 X:320 Y:430 New Grid code With DataGridView1 .Rows.Clear() .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = GridSize(0) : sqL = "SELECT [" + GridOut.ID + "]" .Columns.Add(GridOut.ID, GridOut.ID) : .Columns(0).Visible = False For I = 1 To FieldCount .Columns.Add(FieldList(I - 1), FieldList(I - 1)) .Columns(I).HeaderText = StrConv(FieldList(I - 1), VbStrConv.ProperCase) : .Columns(I).Width = GridCellSize(I - 1) sqL = sqL + ",[" + Trim(FieldList(I - 1)) + "]" ': MsgBox(sqL + "==" + Str(I)) Next sqL = sqL + " FROM [" + GridOut.table_name + "] WHERE " + GridOut.filter_on + " ORDER BY " + GridOut.sort_field ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read Dim ColumnList As New ArrayList() For I = 0 To FieldCount ColumnList.Add(dr(I)) Next .Rows.Add(ColumnList.ToArray()) Loop End With using a tab system Private Sub tab1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles tab1.Selected If tab1.SelectedTab.Text = "Text Convert" Then If txMultiAction.Items.Count = 0 Then Call LoadMultipleCombo() End If If tab1.SelectedTab.Text = "Database" Then btRefresh_Click(sender, e) End If End Sub ==================== Private Sub btRefresh_Click(sender As Object, e As EventArgs) Handles btRefresh.Click txSectionCode.Height = 400 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 .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 End Sub ==================== Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click 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) End Sub ------------------------------------------------------- Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click 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) End Sub -------------------------------------------------- Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick Try Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0) 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 End Sub ----------------------------------------------- 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 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 End Sub ============== MODULE ============== 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 Example Case "copy_it" TXField2.Height = 100 : TXField3.Visible = True : TXField1.Visible = True With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 800 .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 Private Sub LoadGridData() GridOut.field_list = "" : GridOut.filter_on = "" : GridOut.gridCellwidths = "" GridOut.gridWxH = "" : GridOut.sort_field = "" : GridOut.table_name = "" : GridOut.textBoxTLHW_list = "" ' Try sqL = "SELECT [layoutid],[field_list],[filter_on],[gridCellwidths],[gridWxH],[sort_field],[table_name],[textBoxTLHW_list] FROM [layout] WHERE [table_name]='copy_it'" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) If dr.HasRows = True Then dr.Read() GridOut.field_list = dr(1) : GridOut.filter_on = dr(2) : GridOut.gridCellwidths = dr(3) GridOut.gridWxH = dr(4) : GridOut.sort_field = dr(5) : GridOut.table_name = dr(6) : GridOut.textBoxTLHW_list = dr(7) End If 'Loop Catch ex As Exception MsgBox(ex.Message) End Try TXID.Text = "" : TXField1.Text = "" : TXField2.Text = "" : DataGridView1.Columns.Clear() End Sub USING GRID WITH DATASOURCE To bind an MS Access (.mdb) table to a DataGridView in VB.NET, you primarily use the OleDb provider. This process involves establishing a connection, using a DataAdapter to fill a DataTable, and then assigning that table as the DataSource for your grid. Step-by-Step Implementation Import the Namespace: Include the System.Data.OleDb namespace at the very top of your code file to access the necessary data classes. Define the Connection String: For .mdb files (Access 97-2003), use the Microsoft.Jet.OLEDB.4.0 provider. Fill and Bind: Create a DataTable, fill it via an OleDbDataAdapter, and set it as the DataSource for your DataGridView. Code Example Imports System.Data.OleDb Public Class Form1 Private Sub LoadData() ' 1. Define connection string (use Jet for .mdb files) Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:YourDatabasePathYourDatabase.mdb;" Dim sql As String = "SELECT * FROM YourTableName" ' 2. Use a Try-Catch block to handle connection errors Try Using conn As New OleDbConnection(connString) ' 3. Initialize DataAdapter and DataTable Dim da As New OleDbDataAdapter(sql, conn) Dim dt As New DataTable() ' 4. Fill the DataTable with data from the .mdb file da.Fill(dt) ' 5. Bind the DataTable to the DataGridView DataGridView1.DataSource = dt End Using Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load LoadData() End Sub End Class Vb.net 10 05/05/2026 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 4 05/05/2026 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 4 05/05/2026 Vb.net Database Loading Records From Database Into Data Grid data grid datagrid delete read update Web Tools Load Grid With Mdb Imports System.IO Imports System.Text Imports System.Data.OleDb Load data grid05/05/26 Private Sub btAdd_Click_1(sender As Object, e As EventArgs) Handles btAdd.Click sqL = UpdateInfo(0, "add") ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Dim ColumnList As New ArrayList() : ColumnList.Add(0) For I = 1 To GridOut.field_count ColumnList.Add(UpdateInfo("TXField" + Trim(Str(I)), "cells")) Next DataGridView1.Rows.Add(ColumnList.ToArray()) End Sub Private Sub PrepareControl(FindIt As String, CTRLtype As String, Optional BoxHeight As Int16 = 0, Optional ByRef BoxPos As Int16 = 0) ' 'For i As Integer = 1 To 10 Dim key = FindIt Dim hits = Me.Controls.Find(key, True) If hits.Length > 0 Then Select Case CTRLtype Case "labelClear" Dim la = TryCast(hits(0), Label) If la IsNot Nothing Then la.Visible = False Case "textboxClear" Dim tb = TryCast(hits(0), TextBox) If tb IsNot Nothing Then tb.Visible = False : tb.Text = "" Case "textboxDataEntry" Dim tb = TryCast(hits(0), TextBox) If tb IsNot Nothing Then With tb .Top = BoxPos : PrepareControl("LAField" + FindIt.Substring(FindIt.Length - 1, 1), "labelDataEntry", BoxHeight, BoxPos) .Height = BoxHeight * 20 : .Width = 500 'If BoxHeight > 1 Then MsgBox(.Top & "===" & .Height & Str(BoxPos)) : Stop .Left = 320 : BoxPos = BoxPos + BoxHeight * 20 + 3 .Visible = True : .Multiline = False : If BoxHeight > 1 Then .Multiline = True End With End If Case "labelDataEntry" Dim tb = TryCast(hits(0), Label) If tb IsNot Nothing Then tb.Top = BoxPos End If End Select End If 'Next End Sub Private Function LoadGridData() Dim FieldList() As String, tboxSize() As String, GridSize() As String, GridCellSize() As String Dim BoxPos As Int32 = 430, FieldCount As Int16 GridOut.field_list = "" : GridOut.filter_on = "" : GridOut.gridCellwidths = "" : GridOut.ID = "" GridOut.gridWxH = "" : GridOut.sort_field = "" : GridOut.table_name = "" : GridOut.textBoxTLHW_list = "" For I As Integer = 1 To 9 : PrepareControl("LAField" + Trim(Str(I)), "labelClear") : Next For I As Integer = 1 To 9 : PrepareControl("TXField" + Trim(Str(I)), "textboxClear") : Next 'table_selected = "layout" 'SWD test Try sqL = "SELECT [layoutid],[field_list],[filter_on],[gridCellwidths],[gridWxH],[ID],[sort_field],[storage],[table_name],[textBoxTLHW_list] FROM [layout] WHERE [table_name]='" + table_selected + "'" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) If dr.HasRows = True Then dr.Read() GridOut.field_list = dr(1) : GridOut.filter_on = dr(2) : GridOut.gridCellwidths = dr(3) GridOut.gridWxH = dr(4) : GridOut.ID = dr(5) : GridOut.sort_field = dr(6) : GridOut.table_name = dr(8) : GridOut.textBoxTLHW_list = dr(9) End If 'load arrays with values and check proper count FieldList = GridOut.field_list.Split(",") : FieldCount = FieldList.Length : GridOut.field_count = FieldCount GridSize = GridOut.gridWxH.Split(",") : If GridSize.Length <> 3 Then MsgBox("Enter Width,Height, cellheight of grid") : Return False GridCellSize = GridOut.gridCellwidths.Split(",") : If GridCellSize.Length <> FieldCount Then MsgBox("Enter Width of each grid cell") : Return False tboxSize = GridOut.textBoxTLHW_list.Split(",") : If tboxSize.Length <> FieldCount Then MsgBox("Enter each textbox height") : Return False Catch ex As Exception MsgBox(ex.Message) : Return False End Try Try 'POSITION TEXT BOXES BoxPos = GridSize(1) + 4 : grDatabasePick.Top = BoxPos For I = 1 To FieldCount : PrepareControl("TXField" + Trim(Str(I)), "textboxDataEntry", tboxSize(I - 1), BoxPos) : Next For I = 1 To FieldCount 'CLEANUP LABEL FIELDS Dim key = "LAField" + Trim(Str(I)) : Dim hits = Me.Controls.Find(key, True) : Dim tb = TryCast(hits(0), Label) : If tb IsNot Nothing Then tb.Text = StrConv(FieldList(I - 1), VbStrConv.ProperCase) : tb.Visible = True Next 'CUSTOMIZE THE GRID CONTROL With DataGridView1 .DataSource = Nothing : .Columns.Clear() .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = GridSize(0) : .Height = GridSize(1) : .RowTemplate.Height = GridSize(2) : sqL = "SELECT [" + GridOut.ID + "]" '.Columns.Add(GridOut.ID, GridOut.ID) : For I = 1 To FieldCount '.Columns.Add(FieldList(I - 1), FieldList(I - 1)) '.Columns(I).HeaderText = StrConv(FieldList(I - 1), VbStrConv.ProperCase) : .Columns(I).Width = GridCellSize(I - 1) sqL = sqL + ",[" + Trim(FieldList(I - 1)) + "]" Next sqL = sqL + " FROM [" + GridOut.table_name + "] WHERE " + StripSlashes(GridOut.filter_on) + " ORDER BY " + GridOut.sort_field ConnDB() Dim adapter As New OleDbDataAdapter(sqL, conn) Dim builder As New OleDbCommandBuilder(adapter) Dim gridtable As New DataTable() ' 4. Fill the DataTable with data from the .mdb file adapter.Fill(gridtable) .DataSource = gridtable .Columns(0).Visible = False For I = 1 To FieldCount .Columns(I).HeaderText = StrConv(.Columns(I).HeaderText, VbStrConv.ProperCase) : .Columns(I).Width = GridCellSize(I - 1) Next .PerformLayout() End With 'End If Catch ex As Exception MsgBox(sqL) MsgBox(ex.Message) End Try TXID.Text = "" Return True End Function Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then Dim rowID As Object = DataGridView1.Rows(e.RowIndex).Cells(0).Value 'MessageBox.Show($"Row with ID={rowID} (RowIndex={e.RowIndex}) was edited.","Row Edited",MessageBoxButtons.OK, MessageBoxIcon.Information) ' Optional: highlight the edited row DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightYellow UpdateTextboxValue() btUpdate_Click_1(sender, e) End If End Sub Private Sub DataGridView1_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowEnter UpdateTextboxValue() End Sub Private Sub ProcessTextBox(tb As TextBox, boxPos As Int32, tboxSize As String) With tb .Multiline = False : If Int(tboxSize) > 1 Then .Multiline = True .Top = boxPos : LAField1.Top = boxPos .Height = Int(tboxSize(0)) * 20 .Left = 320 : boxPos = boxPos + .Height + 5 .Visible = True End With End Sub Private Sub btRefresh_Click_1(sender As Object, e As EventArgs) Handles btRefresh.Click If LoadGridData() = False Then MsgBox("You have problems In your layout") End Sub Function UpdateTextboxValue() As Boolean Dim I As Int16 = 0 Try Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0) TXID.Text = dr.Cells(0).Value.ToString() For I = 1 To GridOut.field_count Dim hits = Me.Controls.Find("TXField" & Trim(Str(I)), True) : Dim tb = TryCast(hits(0), TextBox) : If tb IsNot Nothing Then tb.Text = dr.Cells(I).Value.ToString() Next Select Case table_selected Case "copy_it" Clipboard.SetText(TXField2.Text, TextDataFormat.UnicodeText) End Select Catch ex As Exception Return False End Try Return True End Function Function UpdateInfo(key As String, ActionDone As String) As String Dim TMP As String, TMP2 As String = "", I As Int16 Select Case ActionDone Case "add" 'sqL = "INSERT INTO [copy_it]([category],[copy_text],[notes]) VALUES ('" + TXField1.Text + "', '" + TXField3.Text + "', '" + TXField2.Text + "')" Dim FieldList() As String = GridOut.field_list.Split(",") TMP = "INSERT INTO [" + GridOut.table_name + "](" For I = 1 To GridOut.field_count TMP = TMP + TMP2 + "[" + Trim(FieldList(I - 1)) + "]" : TMP2 = ", " Next TMP = TMP + ") VALUES (" : TMP2 = "" For I = 1 To GridOut.field_count : TMP = TMP + TMP2 + "'" + AddSlashes(UpdateInfo("TXField" + Trim(Str(I)), "cells")) + "'" : TMP2 = ", " : Next TMP = TMP + ")" Return TMP Case "cells" Dim hits = Me.Controls.Find(key, True) : Dim tb = TryCast(hits(0), TextBox) If tb IsNot Nothing Then Return tb.Text Case "update" Dim FieldList() As String = GridOut.field_list.Split(",") TMP = "UPDATE " + GridOut.table_name + " SET " For I = 1 To GridOut.field_count TMP = TMP + TMP2 + "[" + Trim(FieldList(I - 1)) + "]='" + AddSlashes(UpdateInfo("TXField" + Trim(Str(I)), "cells")) + "'" : TMP2 = ", " Next TMP = TMP + " WHERE [" + GridOut.ID + "]= " + TXID.Text Return TMP End Select Return False End Function Private Sub btUpdate_Click_1(sender As Object, e As EventArgs) Handles btUpdate.Click Dim update As DataGridViewRow = DataGridView1.SelectedRows(0), I As Int16 If TXID.Text = "0" Then MsgBox("You cannot edit new records without refresh.") : Exit Sub For I = 1 To GridOut.field_count update.Cells(I).Value = UpdateInfo("TXField" + Trim(Str(I)), "cells") Next Try sqL = UpdateInfo(TXID.Text, "update") 'Stop ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub rbFilePaths_CheckedChanged(sender As Object, e As EventArgs) Handles rbFilePaths.CheckedChanged If rbFilePaths.Checked = True Then table_selected = "file_paths" : btRefresh_Click_1(sender, e) End Sub Private Sub rbMultireplace_CheckedChanged(sender As Object, e As EventArgs) Handles rbMultireplace.CheckedChanged If rbMultireplace.Checked = True Then table_selected = "mulitreplace" : btRefresh_Click_1(sender, e) End Sub Private Sub rbDirectoryCopy_CheckedChanged(sender As Object, e As EventArgs) Handles rbDirectoryCopy.CheckedChanged If rbDirectoryCopy.Checked = True Then table_selected = "directory_copy" : btRefresh_Click_1(sender, e) End Sub Private Sub RBcopyText_CheckedChanged(sender As Object, e As EventArgs) Handles RBcopyText.CheckedChanged If RBcopyText.Checked = True Then table_selected = "copy_it" : btRefresh_Click_1(sender, e) End Sub Private Sub RBemailFiltered_CheckedChanged(sender As Object, e As EventArgs) Handles RBemailFiltered.CheckedChanged ================================================================= Delete Rows from grid Example: Deleting Selected Row Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click ' Check if any row is selected If DataGridView1.SelectedRows.Count > 0 Then ' Remove the first selected row DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0)) Else MessageBox.Show("Please select a row to delete.") End If End Sub Copy Explanation: SelectedRows: Retrieves the rows selected by the user. Rows.Remove: Deletes the specified row from the DataGridView. Example: Deleting Row by Index If you know the index of the row to delete: Private Sub btnDeleteByIndex_Click(sender As Object, e As EventArgs) Handles btnDeleteByIndex.Click Dim index As Integer = 0 ' Specify the index of the row to delete If index >= 0 AndAlso index < DataGridView1.Rows.Count - 1 Then DataGridView1.Rows.RemoveAt(index) Else MessageBox.Show("Invalid row index.") End If End Sub Copy Important Considerations: Bound Data: If your DataGridView is bound to a data source, you must remove the item from the data source instead of directly removing it from the grid. Uncommitted Rows: Ensure that uncommitted new rows are not targeted for deletion, as this will throw an exception. Validation: Always validate that a row exists before attempting to delete it to avoid runtime errors. Vb.net 6 05/05/2026 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 7 05/05/2026 Vb.net Database Pull In Access Field Names field names access Web Tools Imports System.Data.OleDb ' ... connection setup Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:PathToYourDatabase.accdb;" Using conn As New OleDbConnection(connectionString) conn.Open() Dim query As String = "SELECT * FROM YourTableName" ' Or a specific query Dim cmd As New OleDbCommand(query, conn) Using rdrOLEDB As OleDbDataReader = cmd.ExecuteReader() Console.WriteLine("Field Names:") For i As Integer = 0 To rdrOLEDB.FieldCount - 1 Console.WriteLine(rdrOLEDB.GetName(i)) Next End Using End Using Vb.net 3 05/05/2026 Vb.net Files Directory Files Into A List Box Checking Drive Available delete files directory drive listbox Imports System.IO [DELETE FILE] If File.Exists(TREE3 + FLD(0, 0) + "_header.php") Then File.Delete(TREE3 + FLD(0, 0) + "_header.php") ============== Function DriveAvailable(driveLetter As String) As Boolean Try Dim driveInfo As New DriveInfo(driveLetter) Return driveInfo.IsReady ' Returns True if the drive is ready Catch ex As Exception Return False ' Return False if an exception occurs (e.g., invalid drive) End Try End Function Sub LoadFilesListBox(ByRef coBox As ListBox, ByVal folderPath As String, ByVal Pattern As String) Dim M0 As Integer = 1, fileName1 As String = "", M1 As Integer, M As Integer 'PatternSection As String 'Dim di As New IO.DirectoryInfo(folderPath), diar1 As IO.FileInfo(), dra As IO.FileInfo With coBox .Items.Clear() End With Dim AllowedExtension As String = "*.*" If Not System.IO.Directory.Exists(folderPath) Then MsgBox("This folder seems to have disappeared.") : Exit Sub For Each file As String In IO.Directory.GetFiles(folderPath, "*.*") M1 = file.LastIndexOf("") + 1 : M = file.Length - M1 fileName1 = file.Substring(M1, M) coBox.Items.Add(fileName1) Next End Sub Vb.net 4 05/05/2026 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 1292 05/05/2026 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 1355 05/05/2026 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 1011 05/05/2026 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 2 05/05/2026 Vb.net Files FILE MODIFICATION file date newer File Copy Private Const GENERIC_READ = &H80000000 Private Const GENERIC_WRITE = &H40000000 Private Const FILE_SHARE_READ = &H1 Private Const FILE_SHARE_WRITE = &H2 Private Const CREATE_NEW = 1 Private Const CREATE_ALWAYS = 2 Private Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Private Type SYSTEMTIME wYear As Integer wMonth As Integer wDayOfWeek As Integer wDay As Integer wHour As Integer wMinute As Integer wSecond As Integer wMilliseconds As Integer End Type Private Type TIME_ZONE_INFORMATION Bias As Long StandardName(31) As Integer StandardDate As SYSTEMTIME StandardBias As Long DaylightName(31) As Integer DaylightDate As SYSTEMTIME DaylightBias As Long End Type Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" ( _ ByVal lpFileName As String, ByVal dwDesiredAccess As Long, _ ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, _ ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, _ ByVal hTemplateFile As Long) As Long Private Declare Function CloseHandle Lib "kernel32.dll" ( _ ByVal hObject As Long) As Long Private Declare Function FileTimeToSystemTime Lib "kernel32" (lpFileTime As _ FILETIME, lpSystemTime As SYSTEMTIME) As Long Private Declare Function FileTimeToLocalFileTime Lib "kernel32" (lpFileTime As _ FILETIME, lpLocalFileTime As FILETIME) As Long Private Declare Function LocalFileTimeToFileTime Lib "kernel32.dll" ( _ ByRef lpLocalFileTime As FILETIME, ByRef lpFileTime As FILETIME) As Long Private Declare Function GetFileTime Lib "kernel32.dll" ( _ ByVal hFile As Long, ByRef lpCreationTime As FILETIME, _ ByRef lpLastAccessTime As FILETIME, _ ByRef lpLastWriteTime As FILETIME) As Long Private Declare Function SystemTimeToVariantTime Lib "oleaut32.dll" ( _ ByRef lpSystemTime As SYSTEMTIME, ByRef vtime As Date) As Long Private Declare Function SystemTimeToTzSpecificLocalTime Lib "kernel32.dll" ( _ ByVal lpTimeZoneInformation As Any, ByRef lpUniversalTime As SYSTEMTIME, _ ByRef lpLocalTime As SYSTEMTIME) As Long Const TEST_PATH = "C:MyFile.JPG" Dim hFile As Long, ret As Long '~~> Retrieve the Create date, Modify (write) date and Last Access date of '~~> the specified file Sub GetFileTimeDemo() hFile = CreateFile(TEST_PATH, GENERIC_READ Or GENERIC_WRITE, _ FILE_SHARE_READ Or FILE_SHARE_WRITE, ByVal 0&, CREATE_ALWAYS, 0, 0) Dim ftCreate As FILETIME, ftModify As FILETIME, ftLastAccess As FILETIME Dim ft As FILETIME Dim systime_utc As SYSTEMTIME, systime_local As SYSTEMTIME, snull As SYSTEMTIME Dim tz As TIME_ZONE_INFORMATION Dim CreateDate As Date, LastAccessDate As Date, ModifyDate As Date If hFile = 0 Then Exit Sub '~~> read date information If GetFileTime(hFile, ftCreate, ftLastAccess, ftModify) Then '~~> File CreationDate FileTimeToLocalFileTime ftCreate, ft LocalFileTimeToFileTime ft, ftCreate FileTimeToSystemTime ft, systime_utc CreateDate = DateSerial(systime_utc.wYear, systime_utc.wMonth, _ systime_utc.wDay) + TimeSerial(systime_utc.wHour, systime_utc.wMinute, _ systime_utc.wSecond) + (systime_utc.wMilliseconds / 86400000) Dim ftUTC As FILETIME LocalFileTimeToFileTime ft, ftUTC '~~> File LastAccessedDate FileTimeToSystemTime ftLastAccess, systime_utc SystemTimeToTzSpecificLocalTime ByVal 0&, systime_utc, systime_local SystemTimeToVariantTime systime_local, LastAccessDate '~~> File LastModifiedDate FileTimeToSystemTime ftModify, systime_utc SystemTimeToTzSpecificLocalTime ByVal 0&, systime_utc, systime_local SystemTimeToVariantTime systime_local, ModifyDate End If Dim msg As String msg = "File Create Date/time : " & CreateDate & vbCrLf & _ "File LastAccess Date/time : " & LastAccessDate & vbCrLf & _ "File Last Modified Date/time : " & ModifyDate & vbCrLf '~~> Display the relevant info MsgBox msg, vbInformation, "File Stats" Call CloseHandle(hFile) End Sub Vb.net 2 05/05/2026 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 3 05/05/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 2 05/05/2026 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 5 05/05/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 3 05/05/2026 Vb.net Function Outlook Email outlook move email hidden OUTLOOK To move an email to a deep folder in an Outlook Data File using VB.NET, use the Outlook Object Library to traverse the folder hierarchy via .Folders("Name"). The key is to reference the PST store, navigate down three levels using nested Folders objects, and apply the Move method to the target MailItem. Prerequisites Add a reference to Microsoft.Office.Interop.Outlook. Ensure the Target PST file is already open in Outlook. VB.NET Code Example Imports Outlook = Microsoft.Office.Interop.Outlook Module MoveEmailModule Sub MoveEmailToDeepFolder() Dim outlookApp As New Outlook.Application() Dim namespace As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") ' 1. Get the PST Store (Outlook Data File) ' Replace "MyPSTFile" with the exact name shown in your folder pane Dim pstFolder As Outlook.MAPIFolder = namespace.Folders("MyPSTFile") ' 2. Navigate 3 levels deep Dim targetFolder As Outlook.MAPIFolder = pstFolder.Folders("Folder1") .Folders("Folder2") .Folders("Folder3") ' 3. Select an email (example: first item in Inbox) Dim inbox As Outlook.MAPIFolder = namespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) Dim mailItem As Outlook.MailItem = inbox.Items.GetFirst() ' 4. Move the email If Not mailItem Is Nothing Then mailItem.Move(targetFolder) Console.WriteLine("Email moved successfully.") Else Console.WriteLine("No email found in Inbox.") End If End Sub End Module Key Considerations Hierarchical Paths: You must use the exact folder names, such as .Folders("Root").Folders("Level1").Folders("Level2"). PST Name: The namespace.Folders("Name") must match the top-level name of the data file as it appears in the Outlook navigation pane. Error Handling: Add error handling (Try-Catch) for scenarios where folders do not exist or the PST file is disconnected. 2025 If you're looking to move Outlook emails into an Outlook Data File (.pst) using VB.NET, you can achieve this programmatically using the Outlook Object Model. Here's a breakdown of the process: Understand the Outlook Object Model: The Outlook Object Model provides a set of classes and objects that allow you to interact with various components of Outlook, including emails, folders, and data files. Establish a connection to Outlook: You'll need to create an instance of the Outlook.Application object to start interacting with Outlook. Access the Outlook Data File (.pst): Once connected to Outlook, you can use the Application.Session.Stores collection to access the different data files (including .pst files) currently open in Outlook. Identify the target folder within the .pst file: Navigate through the folders within the .pst file to pinpoint the specific folder where you want to move the emails. Iterate through the emails in the source folder: Locate the emails you intend to move by iterating through the Items collection of the source folder (e.g., Inbox, Sent Items). Move the emails: For each email you want to move, use the MailItem.Move method, specifying the target folder as the destination. Example (Conceptual Outline) This code snippet provides a basic illustration of how you might approach this task in VB.NET. vb.net Imports Outlook Public Class EmailMover Private Sub MoveEmailsToPST() Try Dim outlookApp As New Outlook.Application() Dim olNamespace As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") ' --- Identify the PST file (Outlook Data File) --- Dim targetPST As Outlook.Store = Nothing For Each store As Outlook.Store In olNamespace.Stores If store.DisplayName = "My Outlook Data File" Then ' Replace with the actual name of your PST file targetPST = store Exit For End If Next If targetPST Is Nothing Then MessageBox.Show("Outlook Data File (PST) not found!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If ' --- Identify the target folder within the PST file --- Dim targetFolder As Outlook.MAPIFolder = Nothing For Each folder As Outlook.MAPIFolder In targetPST.GetRootFolder().Folders If folder.Name = "Archive" Then ' Replace with the actual name of your archive folder in the PST targetFolder = folder Exit For End If Next If targetFolder Is Nothing Then MessageBox.Show("Target folder within PST not found!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If ' --- Get the source folder (e.g., Inbox) --- Dim inboxFolder As Outlook.MAPIFolder = olNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) ' --- Loop through the emails in the Inbox and move them --- For Each mailItem As Object In inboxFolder.Items If TypeOf mailItem Is Outlook.MailItem Then Dim email As Outlook.MailItem = DirectCast(mailItem, Outlook.MailItem) ' Add your criteria for moving emails here (e.g., based on sender, subject, date) If email.Subject.Contains("Old Project") Then ' Example: Move emails with "Old Project" in the subject email.Move(targetFolder) MessageBox.Show("Email moved: " & email.Subject, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End If Next MessageBox.Show("Email moving process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) Catch ex As Exception MessageBox.Show("An error occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub End Class Important notes .Contains is case sensitive if (email.subject.toLowerCase().indexOf("INC") > -1) { // Execute code for emails with "INC" in the subject (case-insensitive) // For example, update an incident record } Replace placeholders: Be sure to replace "My Outlook Data File" and "Archive" with the actual names of your Outlook data file (.pst) and the specific folder within it where you want to move the emails. Error Handling: Include robust error handling in your code to address potential issues like missing files, network problems, or access errors. User Interface (UI): If you are developing a desktop application, you can integrate this logic with a user interface that allows the user to select the source and destination folders, apply filters, and initiate the moving process. Security and Permissions: Ensure your application has the necessary permissions to interact with Outlook and access the Outlook Data Files To look for "hidden received from" traces in an email (typically originating IP or server details), you need to parse the raw internet headers. Each SMTP server along an email's route appends a Received header. You can search these header strings to trace hidden hops or server origins. Reading and Analyzing "Received" Headers in VB.NET To extract and check for specific information inside the Received lines, you can use the built-in System.Net.Mail namespace to access message headers. Imports System.Net.Mail Public Sub CheckReceivedHeaders(emailMessage As MailMessage) ' Loop through all headers For Each headerKey As String In emailMessage.Headers.AllKeys If headerKey.Equals("Received", StringComparison.OrdinalIgnoreCase) Then Dim headerValue As String = emailMessage.Headers(headerKey) ' Check for specific servers, IPs, or "Received: from" clauses If headerValue.Contains("hidden-server-name") Or headerValue.Contains("from") Then Console.WriteLine("Found Received Header: " & headerValue) End If End If Next End Sub Important Concepts for Email Tracking Chronological Order: Headers are read from bottom to top. The bottom Received trace is closest to the original sender. Spoofing vs Hidden: While some headers look hidden, a true original Received header will display the original originating server and IP at the very bottom of the chain Third-Party Libraries: The default .NET tools give you string access to headers, but for complex or malformed headers, developers often rely on robust libraries like GemBox.Email o Vb.net 8 06/04/2026 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 2 05/05/2026 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 2 05/05/2026 Vb.net Function Form Events form events Forms Common Events Fired on Minimize Resize Fires whenever the form’s size changes — including minimize, maximize, and restore. SizeChanged Similar to Resize, but occurs after the size change is applied. Layout Fires when the layout of the form or its controls changes. Activated / Deactivate If minimizing causes the form to lose focus, Deactivate will fire. When restored and focused again, Activated will fire. ResizeBegin / ResizeEnd Only fire during manual resizing (dragging edges), not when clicking minimize. Detecting Minimize Specifically You can detect a minimize action by checking the WindowState property inside the Resize or SizeChanged event: Vb.net 2 05/05/2026 Vb.net Ini Read And Write From Ini File ini windows API api Include inside a function routine Public Path As Path_, MarkIt As marker_ Public INI As String, INN As String, LogErr As Integer, RegDir As String, RegSet As String, gBreak As Boolean Public Const vbCR = vbCrLf, vbEmpty = Chr(34) + Chr(34) Public Const VK_ESCAPE& = &H1B, VK_LBUTTON& = &H1 Public gAccess As Integer Declare Auto Function GetPrivateProfileString Lib "kernel32" ( _ ByVal lpAppName As String, _ ByVal lpKeyName As String, _ ByVal lpDefault As String, _ ByVal lpReturnedString As System.Text.StringBuilder, _ ByVal nSize As Integer, _ ByVal lpFileName As String) As Integer Public Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal vKey As Int32) As UShort Declare Auto Function WritePrivateProfileString Lib "kernel32" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer Public Function GetIni(ByVal section As String, ByVal L As String, ByVal fil0$) As String Dim fil$ On Error Resume Next fil$ = fil0$ L = LTrim$(L) Dim R As New System.Text.StringBuilder(256) Dim retVal As Integer = GetPrivateProfileString(section, L, "", R, R.Capacity, fil0$) 'X = GetPrivateProfileString(section, L, "none", R, 50, fil) 'R = Trim(R) : R = Left$(R, Len(R) - 1) Return R.ToString 'GetIni = R End Function Public Function WriteIni(ByVal section$, ByVal L$, ByVal R$, ByVal fil0$) As Integer Dim X As Long, fil$ On Error Resume Next L$ = Trim$(L$) : fil = fil0 X = WritePrivateProfileString(section$, L$, R$, fil) 'If L$ <> "" And fil$ = INI Then Call SetKeyValue(RegSet, L$, R$) Return True End Function R$ = GetIni("Setup", "cloud", INI) WriteIni("Setup", "cloud", "C:UserssteveDropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI) Vb.net 5 05/05/2026 Vb.net Keyboard Clipboard clipboard html text If Clipboard.ContainsText() And TXJoin1.Text = "" Then TXJoin1.Paste() End If Private Sub btClipDir_Click(sender As Object, e As EventArgs) Handles btClipDir.Click Dim FL1 As String, ALLFile As String = "" FL1 = Dir(Path.TREE2 + "") ALLFile = PrintDirectory(Path.TREE2) If ALLFile <> "" Then Clipboard.SetText(ALLFile, TextDataFormat.UnicodeText) End Sub Clear Removes all data from the Clipboard. Public methodStatic member ContainsAudio Indicates whether there is data on the Clipboard in the WaveAudio format. Public methodStatic member ContainsData Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format. Public methodStatic member ContainsFileDropList Indicates whether there is data on the Clipboard that is in the FileDrop format or can be converted to that format. Public methodStatic member ContainsImage Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format. Public methodStatic member ContainsText() Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system. Public methodStatic member ContainsText(TextDataFormat) Indicates whether there is text data on the Clipboard in the format indicated by the specified TextDataFormat value. Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Public methodStatic member GetAudioStream Retrieves an audio stream from the Clipboard. Public methodStatic member GetData Retrieves data from the Clipboard in the specified format. Public methodStatic member GetDataObject Retrieves the data that is currently on the system Clipboard. Public methodStatic member GetFileDropList Retrieves a collection of file names from the Clipboard. Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.) Public methodStatic member GetImage Retrieves an image from the Clipboard. Public methodStatic member GetText() Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system. Public methodStatic member GetText(TextDataFormat) Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value. Public method GetType Gets the Type of the current instance. (Inherited from Object.) Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) Public methodStatic member SetAudio(Byte[]) Clears the Clipboard and then adds a Byte array in the WaveAudio format after converting it to a Stream. Public methodStatic member SetAudio(Stream) Clears the Clipboard and then adds a Stream in the WaveAudio format. Public methodStatic member SetData Clears the Clipboard and then adds data in the specified format. Public methodStatic member SetDataObject(Object) Clears the Clipboard and then places nonpersistent data on it. Public methodStatic member SetDataObject(Object, Boolean) Clears the Clipboard and then places data on it and specifies whether the data should remain after the application exits. Public methodStatic member SetDataObject(Object, Boolean, Int32, Int32) Clears the Clipboard and then attempts to place data on it the specified number of times and with the specified delay between attempts, optionally leaving the data on the Clipboard after the application exits. Public methodStatic member SetFileDropList Clears the Clipboard and then adds a collection of file names in the FileDrop format. Public methodStatic member SetImage Clears the Clipboard and then adds an Image in the Bitmap format. Public methodStatic member SetText(String) Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system. Public methodStatic member SetText(String, TextDataFormat) Clears the Clipboard and then adds text data in the format indicated by the specified TextDataFormat value. Public method ToString Returns a string that represents the current object. (Inherited from Object.) Vb.net 1207 05/05/2026 Vb.net Language Split Variable Into Array explode split Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ") For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next End Sub End Class Vb.net 4 05/05/2026 Vb.net Language Using Try To Catch Errors try errors Mail Dim stream As FileStream = Nothing Try ' Try to open with exclusive access stream = File.Open(TREE3 + FLD(0, 0) + "_header.php", FileMode.Open, FileAccess.ReadWrite, FileShare.None) ' No exception means file is not locked Catch ex As IOException MsgBox(" IOException usually means the file is in use") Catch ex As UnauthorizedAccessException MsgBox("' Could be read-only or permission issue") Finally ' Ensure the stream is closed if it was opened If stream IsNot Nothing Then stream.Close() stream.Dispose() End If End Try ================= Dim tempApp As Outlook.Application, PATH1 As String = Application.StartupPath, BODY As String = "", SECTION1 As String = "", FOUND1 As Boolean = False Dim tempInbox As Outlook.MAPIFolder Dim InboxItems As Outlook.Items Dim J As Int16, i As Integer = 0, Subject As String = "" If Dir(PATH1 + "spamfilter.txt") = "" Then MsgBox("No spam filter. I am leaving") : Exit Sub Dim CODE1 As String = LCase(My.Computer.FileSystem.ReadAllText(PATH1 + "spamfilter.txt")) ' read spam filter Dim FILTER1() As String = Split(CODE1, vbCrLf) 'Dim objattachments, objAttach tempApp = CreateObject("Outlook.Application") 'tempInbox = tempApp.GetNamespace("Mapi").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) tempInbox = tempApp.GetNamespace("Mapi").PickFolder Try InboxItems = tempInbox.Items Catch ex As Exception Console.WriteLine("Can't load Subject" & vbCrLf & ex.Message) MsgBox("nothing is selected") : Exit Sub End Try Dim newMail As Outlook.MailItem For Each newMail In InboxItems Try Subject = newMail.Subject Catch ex As Exception Console.WriteLine("Can't load Subject" & vbCrLf & ex.Message) Continue For End Try Try SECTION1 = LCase(newMail.SenderEmailAddress) Catch ex As Exception Console.WriteLine("Can't load email address" & vbCrLf & ex.Message) Continue For End Try 'SECTION1 = LCase(newMail.SenderName + vbCrLf + newMail.SenderEmailAddress + vbCrLf + newMail.Subject + vbCrLf) 'BODY = LCase(newMail.Body) FOUND1 = False For J = 0 To FILTER1.Count - 1 If InStr(SECTION1, FILTER1(J)) > 0 Then FOUND1 = True : Exit For Next 'If FOUND1 = True Then Continue For If FOUND1 = False Then Try newMail.Delete() Catch ex As Exception Console.WriteLine("Can't delete email address" & vbCrLf & ex.Message) Continue For End Try End If ' End If Next Application.DoEvents() 'Next InboxItems = Nothing tempInbox = Nothing tempApp = Nothing MsgBox("Done") : Exit Sub Vb.net 2 05/05/2026 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 1852 05/05/2026 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 application3 'starts up. This is the equivilent of a4 '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 1217 05/05/2026 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 2 05/05/2026 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 1056 05/05/2026 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 1041 05/05/2026 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 1037 05/05/2026 Vb.net String Using String Keys In Arrays array list key string dictionary Email App Lists It sounds like you want to use a VB.NET ArrayList to populate rows in something like a DataGridView or DataTable using .Rows.Add(). The important thing to know is: .Rows.Add() expects either individual column values or an array of values (e.g., Object()), not an ArrayList directly. If you have an ArrayList, you must convert it to an Object() array before passing it to .Rows.Add(). Example: Using ArrayList with DataGridView.Rows.Add() VbnetImports System.Collections Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Create columns in DataGridView DataGridView1.Columns.Add("ID", "ID") DataGridView1.Columns.Add("Name", "Name") DataGridView1.Columns.Add("Age", "Age") ' Create an ArrayList with row data Dim rowData As New ArrayList() rowData.Add(1) rowData.Add("Alice") rowData.Add(30) ' Convert ArrayList to Object() and add as a row DataGridView1.Rows.Add(rowData.ToArray()) ' Another example with different data Dim rowData2 As New ArrayList() From {2, "Bob", 25} DataGridView1.Rows.Add(rowData2.ToArray()) End Sub End Class Example: Using ArrayList with DataTable.Rows.Add() VbnetImports System.Collections Imports System.Data Module Module1 Sub Main() ' Create DataTable with columns Dim dt As New DataTable() dt.Columns.Add("ID", GetType(Integer)) dt.Columns.Add("Name", GetType(String)) dt.Columns.Add("Age", GetType(Integer)) ' Create ArrayList with row data Dim rowData As New ArrayList() From {1, "Alice", 30} ' Add row by converting ArrayList to Object() dt.Rows.Add(rowData.ToArray()) ' Display results For Each row As DataRow In dt.Rows Console.WriteLine($"{row("ID")} - {row("Name")} - {row("Age")}") Next End Sub End Module Key Points ArrayList is non-generic and stores Object values. .Rows.Add() cannot take an ArrayList directly — you must call .ToArray() to convert it to an Object() array. If you know the type of data, consider using List(Of T) instead of ArrayList for type safety. If you want, I can also show you how to loop through an ArrayList of multiple rows and add them all to a DataGridView in one go. Do you want me to prepare that example? vb.net ' Import the necessary namespace Imports System.Collections Module Module1 Sub Main() ' 1. Create and instantiate the ArrayList Dim myArrayList As New ArrayList() ' 2. Add elements (can be different data types) myArrayList.Add("Hello World") myArrayList.Add(42) myArrayList.Add(True) ' 3. Access an element by index Console.WriteLine("First item: " & myArrayList(0)) ' 4. Iterate through the list For Each item In myArrayList Console.WriteLine(item) Next End Sub End Module AI Overview In VB.NET, standard Array objects are indexed by integers, starting from 0, and do not support string keys. To use string keys (also known as an associative array), you should use the System.Collections.Generic.Dictionary(Of TKey, TValue) class, which is designed for this purpose. Using a Dictionary for String Keys The Dictionary collection allows you to store and retrieve values using a unique string key, which provides the functionality of a string-keyed array. 1. Declaration and Initialization You can declare and initialize a Dictionary(Of String, String) (where both the key and the value are strings) as follows: vb.net Dim fruitColors As New Dictionary(Of String, String) From { {"Apple", "Red"}, {"Pear", "Green"}, {"Banana", "Yellow"} } 2. Adding Items Use the .Add() method to add items to the dictionary: vb.net fruitColors.Add("Grape", "Purple") 3. Accessing Values by Key You can access values directly using the key in parentheses, similar to an array index: vb.net Dim colorOfApple As String = fruitColors("Apple") Console.WriteLine($"The color of an Apple is {colorOfApple}") ' Output: The color of an Apple is Red 4. Checking for Key Existence Use the .ContainsKey() method before accessing a value to avoid errors if the key does not exist: vb.net Dim input As String = "Kiwi" If fruitColors.ContainsKey(input) Then Console.WriteLine($"The color of a {input} is {fruitColors(input)}") Else Console.WriteLine($"Color for {input} not found.") End If 5. Retrieving All Keys You can get all the keys from the dictionary into a string array or a List(Of String): Using a List: vb.net Dim keyList As New List(Of String)() For Each kvp As KeyValuePair(Of String, String) In fruitColors keyList.Add(kvp.Key) Next ' Convert the List to an array if needed: Dim keyArray() As String = keyList.ToArray() For more details, refer to the official Microsoft documentation on the Dictionary class. Vb.net 3 05/05/2026 Vb.net Variables Create New Arrays array null dimension optional textbox control Arrays Private Sub PrepareControl(FindIt As String, CTRLtype As String, Optional Ar As String() = Nothing, Optional BoxPos As Int16 = 0) For i As Integer = 1 To 10 Dim key = FindIt & i Dim hits = Me.Controls.Find(key, True) If hits.Length > 0 Then Select Case CTRLtype Case "labelClear" Dim la = TryCast(hits(0), Label) If la IsNot Nothing Then la.Visible = False Case "textboxClear" Dim tb = TryCast(hits(0), TextBox) If tb IsNot Nothing Then tb.Visible = False Case "textboxDataEntry" Dim tb = TryCast(hits(0), TextBox) If tb IsNot Nothing Then With tb .Visible = False End With End If End Select End If Next End Sub PrepareControl("LAField", "labelClear") : PrepareControl("TXField", "textboxClear") OR PrepareControl("TXField", "textboxDataEntry", tboxSize, BoxPos) In VB.NET, arrays are fixed-size once created, but you can make them dynamic by using ReDim (and optionally Preserve to keep existing data). If you need a truly dynamic structure, you might use List(Of T) instead. 1. Dynamic Array with ReDim VbnetModule Module1 Sub Main() ' Declare a dynamic array (no size yet) Dim numbers() As Integer ' Set initial size (5 elements, index 0–4) ReDim numbers(4) ' Assign values For i As Integer = 0 To numbers.Length - 1 numbers(i) = i * 10 Next ' Resize array to hold more elements (keep old values) ReDim Preserve numbers(9) ' Add new values For i As Integer = 5 To numbers.Length - 1 numbers(i) = i * 10 Next ' Display all values For Each num In numbers Console.WriteLine(num) Next End Sub End Module Key points: ReDim changes the size of the array. Preserve keeps existing data; without it, the array is cleared. Only the last dimension can be resized with Preserve. 2. Dynamic Multi-Dimensional Array VbnetModule Module1 Sub Main() ' Declare a 2D array Dim matrix(,) As Integer ' Initial size: 2 rows × 3 columns ReDim matrix(1, 2) ' Fill values For r As Integer = 0 To 1 For c As Integer = 0 To 2 matrix(r, c) = (r + 1) * (c + 1) Next Next ' Resize: only last dimension can be preserved ReDim Preserve matrix(1, 4) ' Now 2 rows × 5 columns ' Display For r As Integer = 0 To matrix.GetUpperBound(0) For c As Integer = 0 To matrix.GetUpperBound(1) Console.Write(matrix(r, c) & vbTab) Next Console.WriteLine() Next End Sub End Module ? Limitation: You cannot Preserve more than the last dimension in a multi-dimensional array. 3. Recommended Alternative — List(Of T) For truly dynamic resizing without ReDim limitations: VbnetImports System.Collections.Generic Module Module1 Sub Main() Dim numbers As New List(Of Integer) ' Add elements dynamically numbers.Add(10) numbers.Add(20) numbers.Add(30) ' Insert at specific position numbers.Insert(1, 15) ' Remove element numbers.Remove(20) ' Display For Each num In numbers Console.WriteLine(num) Next End Sub End Module ? List(Of T) is more efficient and flexible than resizing arrays repeatedly. If you want, I can show you a dynamic jagged array in VB.NET, which allows resizing each row independently — this avoids the Preserve limitation for multi-dimensional arrays. Do you want me to prepare that example? 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 3 05/05/2026 VBscript Function Open An Application Like Notepad And File Using Your Browser load application PhpScript INI WSFTP INI ftpClient INI CopyFiles INI Macromedia INI VBscript 1549 05/05/2026 Windows <=8 Customizing Creating Your Own Menu Using The Windows Toolbar toolbar too bar desktop desk top right click folder task bar Even though it is cool using the bricks in the start menu I still like putting my favorite apps on the windows task bar without pinning. It takes up a lot less space. To do this: Right click on the desk top and create a new folder. Give it a Short name so it does not take up much space on the tool bar I like my desk top clean so I just dragged and dumped everything I use a lot on this folder. You will need to copy and paste if you want an icon to stay on the desk top. Leave the folder on your desktop. Right click on the task bar and click on toolbars-new toolbar. From the dialogue box select the Desktop. Select the file folder that you named. You now have all your favorites on the task bar. After you reboot the will be list by alpha. Windows <=8 1298 05/05/2026 Windows <=8 Customizing Making Changes To Your Computer auto dim pc settings control panel Like windows 7 you can use the control panel to adjust the power management and hardware settings. Windows 8 has the PC Settings in the right bar under "SETTINGS" that also has options. My Samsung computer would dim every time it would boot up and I would take it to the place I bought and could not create it. After several hours of frustration I found an auto dim setting that I unchecked. Make sure you look here also Windows <=8 1918 05/05/2026 Windows <=8 Customizing Updating To Windows 10 windows 10 update My computer does not give me the option to update to 10. I found this link which may help. https://www.microsoft.com/en-us/software-download/windows10 Windows <=8 890 05/05/2026 Windows <=8 Customizing To Increase Virtual Memory In Windows 8.1 virtual memory performance Windows To increase virtual memory in Windows 8.1, open System Properties, go to the Advanced tab, click Settings under Performance, then click Change under Virtual Memory. Uncheck Automatically manage paging file size for all drives, select your desired drive, choose Custom size, and input an Initial size (MB) and Maximum size (MB). A common recommendation is an initial size of 1.5 times your RAM and a maximum size of 3 times your RAM, converted to MB (1 GB = 1024 MB). Click Set, then OK, and restart your computer for the changes to take effect. Step-by-step guide to increase virtual memory in Windows 8.1: 1. Access System Properties: Press the Windows key + X and select System, or right-click on "Computer" (or "This PC") and select Properties. 2. Navigate to Advanced System Settings: In the System window, click on Advanced system settings on the left-hand side. 3. Open Advanced -> Performance -> Settings: In the System Properties dialog box, go to the Advanced tab and click the Settings button under the Performance section. Access Virtual Memory Settings: In the Performance Options window, go to the Advanced tab, then click the Change button under the Virtual memory section. Disable Automatic Management: Uncheck the box that says "Automatically manage paging file size for all drives". Set Custom Size: Select your desired drive (usually the C: drive) and choose the "Custom size" option. Enter Initial and Maximum Sizes: In the Initial size (MB) and Maximum size (MB) fields, enter your desired values. -- Recommendation: Set the initial size to 1.5 times your installed RAM and the maximum size to 3 times your installed RAM. -- Conversion: Remember that 1 GB is equal to 1024 MB. Apply and Confirm: Click Set, then OK to close the Performance Options window, and click OK again to close the System Properties window. Restart Your Computer: A restart is required for the new virtual memory settings to take effect. Windows <=8 3 05/05/2026