Notes ACCESS 2022 | Browsers | Css | Htacess | Html | Html5 | Javascript | Microsoft Excel | Mysql | Mysql Dumps | Php | Vb.net | VBscript | Windows <=8 | Windows >=10 | WP | WP Plugin | WP Themes | _Misc Software | ABCDEFGHIJKLMNOPQRSTUVWXYZONPRTOFF codeid operationid title keywords application code languageid show_html show_iframe make_public viewed viewed_date language operation <- Look Inside DataConditions:Order: 47 Language Operation Title Keywords Application Code Languageid Show Html Show Iframe Make Public Viewed Viewed Date Vb.net Archive Email Remove Sub email move Outlook Mail Cleaner Function EmailCriteria() 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 Return MV End Function Private Sub BTmoveEmail_Click(sender As Object, e As EventArgs) Handles BTmoveEmail.Click BypassDialog = True BTMoveAll_Click(sender, e) BTtest_Click(sender, e) Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email Moving And Deleting completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) BypassDialog = False End Sub Private Sub BTMoveAll_Click(sender As Object, e As EventArgs) Handles BTMoveAll.Click Dim outlookApp As New Outlook.Application() Dim lastFolder As String = "", currentFolder As String = "", currentSubject As String = "", currentType As String = "", currentEmail As String = "" Dim emailsMoved As Int16 = 100, MV(200, 2) As String, L As Integer = 0 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") ' Specify the path to the Outlook Data File (PST) Dim pstFilePath As String = GetIni("OutlookDataFile", My.Computer.Name, INI), TMP As String = "" Dim pstDisplayName As String = "receipts" ' Loop through all accounts in Outlook For Each account As Outlook.Account In namespaceMAPI.Accounts 'LOOP THROUGH ACCOUNTS LAcaption.Text = "Moving in account: " & account.DisplayName : Application.DoEvents() emailsMoved = 100 ' Access the Inbox folder of the account Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTMoveAll:" & ex.Message End Try 'start loop here 'Do While emailsMoved > 0 'LOOP THROUGH FOR MISSED EMAIL emailsMoved = 0 MV = EmailCriteria() For i As Integer = inbox.Items.Count To 1 Step -1 'LOOP THROUGH INBOX backwards LEVEL 2 Try Dim email As Outlook.MailItem = TryCast(inbox.Items(i), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If For L = 0 To MV.GetUpperBound(0) 'MsgBox(fruit) currentFolder = MV(L, 0) : currentSubject = MV(L, 1) : currentType = MV(L, 2) add these lines back If lastFolder <> currentFolder Then lastFolder = currentFolder Try targetFolder = namespaceMAPI.Folders("Outlook Data File").Folders(currentFolder) Catch ex As Exception 'M("Error Outlook Data File: " & ex.Message) 'Continue Do End Try End If Select Case currentType Case "1" 'email If email.SenderEmailAddress.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 Exit For End If Case "2" If email.Subject.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 Exit For End If End Select Next 'NEXT L Catch ex As Exception MsgBox("Error moving: " + currentEmail & ex.Message) End Try Next 'LOOP THROUGH INBOX backwards LEVEL 2 END 'end primary loop 'Loop 'LOOP THROUGH FOR DR 'Loop 'LOOP THROUGH FOR MISSED EMAIL END Next 'LOOP THROUGH ACCOUNTS END If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email moving process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Private Sub BTtest_Click(sender As Object, e As EventArgs) Handles BTtest.Click Dim outlookApp As New Outlook.Application() Dim currentEmail As String = "" Dim emailsDeleted As Int16 = 100 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") 'Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim J As Int16, K As Int16, I As Integer = 0, Subject As String = "", FILTER1(200) As String, emailCount As Integer = 0, sql As String = "", Found As Boolean = False 'Readfilter data from mdb Try sql = "SELECT [email] FROM [filtered_email] WHERE [importance]>0 ORDER BY [importance] DESC,[email]" ConnDB() cmd = New OleDbCommand(sql, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) J = 0 Do While dr.Read FILTER1(J) = dr(0) J += 1 Loop emailCount = J - 1 Catch ex As Exception LAerrorMessage.Text = "error BTtestDB:" & ex.Message End Try ' Loop through all accounts in Outlook For Each account As Outlook.Account In namespaceMAPI.Accounts LAcaption.Text = "Deleting In account: " & account.DisplayName : Application.DoEvents() emailsDeleted = 100 ' Access the Inbox folder of the account 'Dim pstRootFolder As Outlook.MAPIFolder = namespaceMAPI.Folders(pstDisplayName) Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTtest account:" & ex.Message End Try 'start loop here Do While emailsDeleted > 0 emailsDeleted = 0 For I = inbox.Items.Count To 1 Step -1 'swd count backwards Try Dim email As Outlook.MailItem = TryCast(inbox.Items(I), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If For K = 0 To emailCount - 1 If email.SenderEmailAddress.Contains(FILTER1(K)) Then Found = True : Exit For Next If Found = False Then email.Delete() emailsDeleted = emailsDeleted + 1 End If Found = False Catch ex As Exception MsgBox(currentEmail & ex.Message) emailsDeleted = emailsDeleted - 1 End Try Next 'end cut A Loop Next If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email Deleting process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub ========================== Outdated ================================ Private Sub BTbulkMove_Click(sender As Object, e As EventArgs) Handles BTbulkMove.Click Dim outlookApp As New Outlook.Application() Dim lastFolder As String = "", currentFolder As String = "", currentSubject As String = "", currentType As Byte = 0, currentEmail As String = "" Dim emailsMoved As Int16 = 100 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") ' Specify the path to the Outlook Data File (PST) Dim pstFilePath As String = GetIni("OutlookDataFile", My.Computer.Name, INI) Dim pstDisplayName As String = "receipts" ' Loop through all accounts in Outlook Try sqL = "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 For Each account As Outlook.Account In namespaceMAPI.Accounts LAcaption.Text = "Moving in account: " & account.DisplayName : Application.DoEvents() emailsMoved = 100 ' Access the Inbox folder of the account Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTbulkMoveA:" & ex.Message End Try 'start loop here Do While emailsMoved > 0 emailsMoved = 0 Try sqL = "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 currentFolder = dr(0) : currentSubject = dr(1) : currentType = dr(2) If lastFolder <> currentFolder Then lastFolder = currentFolder Try targetFolder = namespaceMAPI.Folders("Outlook Data File").Folders(currentFolder) Catch ex As Exception 'M("Error Outlook Data File: " & ex.Message) Continue Do End Try End If For i As Integer = inbox.Items.Count To 1 Step -1 'swd count backwards Try Dim email As Outlook.MailItem = TryCast(inbox.Items(i), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If Select Case currentType Case 1 'email If email.SenderEmailAddress.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 End If Case 2 If email.Subject.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 End If End Select Catch ex As Exception MsgBox("Error moving: " + currentEmail & ex.Message) End Try Next Loop Loop Next If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email moving process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) Vb.net 7 02/26/2026 Vb.net Controls Combo Box Control combo value archive example txMultiAction.Items.Clear() txMultiAction.ValueMember = "replaceid" txMultiAction.DisplayMember = "title" txMultiAction.DataSource = ds.Tables(Table_) 'created from query. See create recordset txMultiAction.SelectedValue 'read database value ================================================== Private Sub txMultiAction_SelectedIndexChanged(sender As Object, e As EventArgs) Handles txMultiAction.SelectedIndexChanged Dim B1 As String = GetIni("Setup", "cloud", Path.TREE + "MenuJS.ini") If B1 = "" Then B1 = Path.TREE Dim Table_ As String = "mulitreplace WHERE replaceid=" + Str(txMultiAction.SelectedValue) 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(2)) 'Dim NextListItem As New ListViewItem(Item) 'ListView1.Items.Add(NextListItem) Next End Sub +++++++++++++++++++++++++++++++++++++++++++++++++ Private Sub btMultiAction_Click(sender As Object, e As EventArgs) Handles btMultiAction.Click Dim fileReader As System.IO.StreamReader, B As String = txText.Text, Action1 As Boolean = False, B1 As String = "" Dim P$(3), POS%(5) Dim A As String = "", A2 As String = "", Action0(-1) As String Dim L10 As Integer = 10, L13 As Integer = 13, Index As Integer = coReplace.SelectedIndex, C1Length As Integer = 0, LOOPOFF As Boolean = False Dim TMPstart As String = "", TMPend As String = "", J As Integer = 0 B1 = GetIni("Setup", "cloud", Path.TREE + "MenuJS.ini") If B1 = "" Then B1 = Path.TREE fileReader = My.Computer.FileSystem.OpenTextFileReader(B1 + "multiaction.txt") Dim stringReader As String ' MsgBox("The first line of the file is " & stringReader) Do Until fileReader.EndOfStream stringReader = fileReader.ReadLine() If stringReader <> "" Then If stringReader.Substring(0, 2) = "[{" Then Action1 = False 'FOUND THE NEXT SECTION. TIME TO STOP READING ON If stringReader = "[{" + txMultiAction.Text + "}]" Then Action1 = True : Continue Do If Action1 = True Then If InStr(stringReader, "?") = 0 Then MsgBox("Invalid Format. A ? needs to be between the search for and replace term", MsgBoxStyle.AbortRetryIgnore) : fileReader.Close() : Exit Sub Action0 = Split(stringReader, "?") : A = Action0(0) : A2 = Action0(1) : If A2 = "NULL" Then A2 = "" 'CREATE LOOKUP STRING AND IDENTIFY REPLACEMENT STRIN Select Case A Case "bof" 'BEGIN OF FILE B = A2 + B Case "eof" 'END OF FILE B = B + A2 Case Is = "lf" 'remove double CrLf B = Replace(B, Chr(10) + Chr(32), Chr(10)) 'remove spaces after feeds 'If InStr(B, Chr(13) + Chr(10)) > InStr(B, Chr(10) + Chr(13)) Then L10 = 13 : L13 = 10:B = Replace(B, Chr(L13) + Chr(L10) + Chr(L13) + Chr(L10), Chr(13) + Chr(10)):B = Replace(B, Chr(13) + Chr(13), Chr(13)) B = Replace(B, Chr(10) + Chr(10), Chr(10)) 'Double feeds to single Case Is = "td" 'Replace tabs with dash B = Replace(B, Chr(9), " - ") Case Is = "ts" 'tab to spaces B = Replace(B, Chr(9), Chr(32)) : B = Replace(B, Chr(32) + Chr(32), Chr(32)) Case Is = "tc" 'tab to comma B = Replace(B, Chr(9), ", ") : B = Replace(B, Chr(32) + ",", ",") Case Is = "lfc" 'replace line feeds with commas B = Replace(B, Chr(10), ", ") B = Replace(B, Chr(10), ", ") : B = Replace(B, ",,", ",") : B = Replace(B, Chr(9), Chr(32)) Case Is = "lb-" 'Replace line breaks with - B = Replace(B, Chr(10), " - ") : B = Replace(B, Chr(9), Chr(32)) : B = Replace(B, Chr(32) + Chr(32), Chr(32)) Case Is = "{GET}" 'EXTRACT BETWEEN { } Dim POS1(3) As Integer POS1(3) = 1 : A2 = "" Do POS1(0) = InStr(POS1(3), B, "{") : POS1(3) = POS1(0) + 1 : POS1(1) = InStr(POS1(3), B, "}") If POS1(0) = 0 Or POS1(1) = 0 Then Exit Do A2 = A2 + B.Substring(POS1(0), POS1(1) - POS1(0) - 1) + vbCrLf Loop If A2 <> "" Then B = A2 Case Is = "{DEL}" 'Delete BETWEEN { } Dim POS1(3) As Integer POS1(3) = 1 Do POS1(0) = InStr(POS1(3), B, "{") If POS1(0) = 0 Then Exit Do POS1(3) = POS1(0) : POS1(1) = InStr(POS1(3), B, "}") : A2 = "" If POS1(0) > 1 Then A2 = B.Substring(0, POS1(0) - 1) B = A2 + B.Substring(POS1(1), B.Length - POS1(1)) 'Build string without first {} Loop Case Else If chAppendCRLF.Checked = True Then A = Replace(A, "|", Chr(10)) : A2 = Replace(A2, "|", Chr(10)) 'REPLACE LINE BREAKS IF IDENTIFIED End If If chAciiConversion.Checked = True Then 'THIS DOES ASCII SOMETHING L10 = InStr(A, "~") If L10 > 0 Then L13 = InStr(L10 + 1, A, "~") End If If L10 > 0 And L13 > 0 Then If L10 > 1 Then TMPstart = A.Substring(0, L10 - 1) If L13 < A.Length Then TMPend = A.Substring(L13, A.Length - L13) A = Chr(Val(A.Substring(L10, L13 - L10 - 1))) End If A = TMPstart + A + TMPend : TMPstart = "" : TMPend = "" 'MsgBox(A) L10 = 0 : L13 = 0 : L10 = InStr(A2, "~") If L10 > 0 Then L13 = InStr(L10 + 1, A2, "~") End If If L10 > 0 And L13 > 0 Then If L10 > 0 And L13 > 0 Then If L10 > 1 Then TMPstart = A2.Substring(0, L10 - 1) If L13 < A2.Length Then TMPend = A2.Substring(L13, A2.Length - L13) A2 = Chr(Val(A2.Substring(L10, L13 - L10 - 1))) End If A2 = TMPstart + A2 + TMPend : TMPstart = "" : TMPend = "" End If End If B = Replace(B, A, A2) End Select End If Loop fileReader.Close() : txText.Text = B End Sub Vb.net 4 07/27/2025 Vb.net Controls How To Use MSGBOX YES NO message box Decision vate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim payed As Integer Dim balance As Integer Dim paying As Integer Dim d As Integer Dim c As Integer Try Dim ans As Integer If TextBox7.Text = "" Or 0 Then MsgBox("please enter amount", MsgBoxStyle.Critical) Else If TextBox6.Text = 0 Then MsgBox("the student is fully payed", MsgBoxStyle.Critical) Else ans = MsgBox(" are you want to upadate the students payment? ", MsgBoxStyle.YesNo, "confirm ") If MsgBoxResult.Yes Then payed = Val(TextBox5.Text) balance = Val(TextBox6.Text) paying = Val(TextBox7.Text) d = payed + paying c = balance - paying TextBox5.Text = d TextBox6.Text = c Dim SqlQuery = "UPDATE sample SET [Payed Amount] ='" & TextBox5.Text & "',Balance ='" & TextBox6.Text & "' WHERE ID = " & a & " ; " Dim sqlcommand As New OleDbCommand With sqlcommand .CommandText = SqlQuery .Connection = conn .ExecuteNonQuery() End With MsgBox("student payment succesfully updated") My.Computer.Audio.Play(My.Resources.CASHREG, AudioPlayMode.Background) If TextBox6.Text = 0 Then MsgBox("the student is now fully paid", MsgBoxStyle.Information) TextBox7.Text = "" Else MsgBox("students current balance is " & Convert.ToString(TextBox6.Text)) LoadListView() TextBox7.Text = "" End If Else Exit Sub End If End If End If Catch ex As Exception MsgBox(ex.Message) End Try Vb.net 0 12/11/2023 Vb.net Controls DoEvents In .NET doevents Developer 18 Application.DoEvents() Vb.net 0 12/14/2023 Vb.net Controls Simple Drag Drop Example drag drop mousedown Developer Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Populate the ListBox with file paths ListBox1.Items.Add("C:examplefile1.txt") ListBox1.Items.Add("C:examplefile2.txt") ListBox1.Items.Add("C:examplefile3.txt") ' Enable drag-and-drop functionality ListBox1.AllowDrop = False End Sub Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown ' Check if an item is selected If ListBox1.SelectedItem IsNot Nothing Then ' Get the selected file path Dim filePath As String = ListBox1.SelectedItem.ToString() ' Ensure the file exists before attempting to drag If IO.File.Exists(filePath) Then ' Start the drag-and-drop operation Dim files() As String = {filePath} Dim dataObject As New DataObject(DataFormats.FileDrop, files) ListBox1.DoDragDrop(dataObject, DragDropEffects.Copy) End If End If End Sub End Class Key Points: File Paths in ListBox: The ListBox should contain valid file paths that exist on the system. Drag-and-Drop Operation: The DoDragDrop method is used to initiate the drag-and-drop operation, passing the file paths as a DataObject with the DataFormats.FileDrop format. MouseDown Event: The drag operation starts when the user clicks and holds the mouse button on a selected item. How It Works: When the user clicks on an item in the ListBox and drags it, the application checks if the item is a valid file path. If valid, the file path is passed to the DoDragDrop method, allowing the user to drop the file into File Explorer or other compatible applications. This approach ensures a smooth drag-and-drop experience while maintaining proper validation of file paths. I just dragged a file from my application to File Explorer using this code: VB.NET: Imports System.Collections.Specialized Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown Dim data As New DataObject() Dim filePaths As New StringCollection filePaths.Add(Path.Combine(Application.StartupPath, "TestData.txt")) data.SetFileDropList(filePaths) DoDragDrop(data, DragDropEffects.Copy) End Sub If you are doing drag and drop just within your application then you can use whatever you want as that first argument to DoDragDrop and look for that same type when dropping. If you're doing it between applications then you do as I have here, i.e. create a DataObject, add data to it in the appropriate format(s) and then pass that to DoDragDrop. That will ensure that any application that supports drag and drop between applications will be able to access that data in the appropriate standard format. That DataObject class also has SetText, SetImage and SetAudio methods for specific data types and a SetData method for everything else. They are the complementary methods to the e.Data.GetX methods you call in a DragDrop event handler. Why is my data not saved to my database? Certainly! If you want to drag items from a ListBox in VB.NET and treat them as files rather than strings, you can achieve this by handling the DragDrop and DragEnter events. Below is an example of how you can implement this: Step-by-Step Implementation Set up the ListBox for Drag-and-Drop: Enable drag-and-drop for the ListBox. Handle the MouseDown event to initiate the drag operation. Handle DragEnter and DragDrop Events: Ensure the target control accepts the dragged data. Handle the drop operation to process the files. Example Code Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Enable drag-and-drop for the ListBox ListBox1.AllowDrop = True ' Add some items to the ListBox ListBox1.Items.Add("C:pathtofile1.txt") ListBox1.Items.Add("C:pathtofile2.txt") End Sub Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown If ListBox1.SelectedItem IsNot Nothing Then ' Start the drag-and-drop operation with the selected item as a file ListBox1.DoDragDrop(New DataObject(DataFormats.FileDrop, New String() {ListBox1.SelectedItem.ToString()}), DragDropEffects.Copy) End If End Sub Private Sub ListBox1_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox1.DragEnter ' Check if the data being dragged is a file If e.Data.GetDataPresent(DataFormats.FileDrop) Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.None End If End Sub Private Sub ListBox1_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox1.DragDrop ' Handle the drop operation If e.Data.GetDataPresent(DataFormats.FileDrop) Then Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String()) For Each file As String In files ListBox1.Items.Add(file) Next End If End Sub End Class Explanation Form Load Event: Enables drag-and-drop for the ListBox. Adds some initial file paths to the ListBox. MouseDown Event: Initiates the drag-and-drop operation when an item is selected and the mouse button is pressed. DragEnter Event: Checks if the data being dragged is a file and sets the appropriate effect. DragDrop Event: Handles the drop operation by adding the dropped files to the ListBox. This code allows you to drag items from the ListBox and treat them as files, making it easier to integrate with other file-based operations. If you have any further questions or need additional customization, feel free to ask! Example One Drag And Drop Controls Using Vb.Net 2.Drag and Drop operation-simple example 2.1. Basic drag & drop operation example Let's look at some examples, starting with simple drag and drop operation. Create a Visual Basic. net windows application and design a form with control & Drag Drop event procedure as follows To enable drag & drop for text 1. Place two textboxes and set Allowdrop property of a second textbox to true. 2. Add the following code Private MouseIsDown As Boolean = False 'variable declaration Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown 'Set a flag to show that the mouse is down. MouseIsDown = True End Sub Private Sub TextBox1_MouseMove(ByVal sender As Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseMove If MouseIsDown Then ' Initiate dragging. TextBox1.DoDragDrop(TextBox1.Text,DragDropEffects.Copy) End If MouseIsDown = False End Sub Private Sub TextBox2_DragEnter(ByVal sender As Object, ByVal e As _ System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter 'Check the format of the data being dropped. If (e.Data.GetDataPresent(DataFormats.Text)) Then ' Display the copy cursor. e.Effect = DragDropEffects.Copy Else ' Display the no-drop cursor. e.Effect = DragDropEffects.None End If End Sub Private Sub TextBox2_DragDrop(ByVal sender As Object, ByVal e As _ System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop 'Paste the text. TextBox2.Text = e.Data.GetData(DataFormats.Text) End Sub In the above example, the MouseDown event is used to set a flag showing that the mouse is down, and then the DoDragDrop method is called in the MouseMove event. Although you could initiate the drag in the MouseDown event, doing so would create undesirable behavior: Every time a user clicks the control, the no-drag cursor would be displayed. T Vb.net 4 05/25/2025 Vb.net Customizing How To: Rename A File In Visual Basic rename file You don't need to mention the complete file path in newFileName parameter, just mention new file name here otherwise you will get ArgumentException. Dim filePath As String = "C:fingerprint1" If File.Exists(filePath) Then Dim strNewFileName As String = "Fingerprint221" My.Computer.FileSystem.RenameFile(filePath, strNewFileName) End If See also Use the RenameFile method of the My.Computer.FileSystem object to rename a file by supplying the current location, file name, and the new file name. This method cannot be used to move a file; use the MoveFile method to move and rename the file. To rename a file Use the My.Computer.FileSystem.RenameFile method to rename a file. This example renames the file named Test.txt to SecondTest.txt. VB Copy ' Change "c:test.txt" to the path and filename for the file that ' you want to rename. My.Computer.FileSystem.RenameFile("C:Test.txt", "SecondTest.txt") This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File system - Processing Drives, Folders, and Files. For more information, see Code Snippets. Vb.net 0 12/09/2023 Vb.net Customizing Code Behinnd MR Button Webtools chr MR Web Tools ? seperates values chr(032032?chr(032 use ascii "bof" BEGIN OF FILE "eof" END OF FILE "lf" remove double CrLf "td" Replace tabs with dash "ts" tab to spaces "tc" tab to comma "lfc" replace line feeds with commas "lb-" Replace line breaks with - "{GET}" EXTRACT BETWEEN { } "{DEL}" 'Delete BETWEEN { } Vb.net 0 11/29/2024 Vb.net Customizing Running A 3rd Party Application computer name shell write 3rd Party Software ou should consider using Process.Start instead of Shell, as Shell is a holdover from the VB 6 days and Process.Start is built into the .NET Framework. Here is an example of running Microsoft Word via the command line, passing it parameters, including file name and any flags: Sub Main() OpenMicrosoftWord("C:UsersSamDocumentsOfficeGears.docx") End Sub ''' ''' Open the path parameter with Microsoft Word. ''' Private Sub OpenMicrosoftWord(ByVal f As String) Dim startInfo As New ProcessStartInfo startInfo.FileName = "WINWORD.EXE" startInfo.Arguments = f Process.Start(startInfo) End Sub ============================== old school Dim R As String = My.Computer.Name ' R = GetIni("Database", R, INI) If R = "" Then WriteIni("Database", My.Computer.Name, "Dropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI) Shell("write.exe " + INI, vbNormalFocus) : Exit Sub End If Vb.net 2 07/27/2025 Vb.net Customizing Close Running Processes application close running Windows VB.Net Close window by title Top Answer Answered Jun 29, 2012 · 6 votes Try using something like this. using Process.MainWindowTitle to get the Title Text and Process.CloseMainWindow to close down the UI, its a little more graceful than killing the Process. Note: Contains does a case-sensitive search Imports System.Diagnostics Module Module1 Sub Main() Dim myProcesses() As Process = Process.GetProcesses For Each p As Process In myProcesses If p.MainWindowTitle.Contains("Notepad") Then p.CloseMainWindow() End If Next End Sub End Module Display processes running Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click File1.Items.Clear() For Each p In Process.GetProcesses If p.MainWindowTitle <> "" Then 'File1.Items.Add(p.MainWindowTitle + "..running") File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]") End If Next End Sub Vb.net 1 07/21/2025 Vb.net Customizing Debug Properties Of Project signing compile debug settings Vb 22 under the menu "debug" look for "xxxx debug properties" Application compile debug references resources services Settings signing my extension's security publish code analysis. Vb.net 0 02/05/2025 Vb.net Customizing Handling Directories directory Developer Creating Directories If Not System.IO.Directory.Exists(YourPath) Then System.IO.Directory.CreateDirectory(YourPath) End If Vb.net 0 03/23/2025 Vb.net Customizing Move Emails From Multiple Accounts To An Outlook Data File multiple accounts move email flag OUTLOOK Imports Microsoft.Office.Interop.Outlook Module Module1 Sub Main() ' Initialize Outlook application Dim outlookApp As New Application() Dim namespaceMAPI As [NameSpace] = outlookApp.GetNamespace("MAPI") ' Specify the path to the Outlook Data File (PST) Dim pstFilePath As String = "C:PathToYourDataFile.pst" Dim pstDisplayName As String = "Archived Emails" ' Add the PST file to Outlook if not already added Try namespaceMAPI.AddStore(pstFilePath) Catch ex As Exception Console.WriteLine("PST file already added or an error occurred: " & ex.Message) End Try ' Get the root folder of the PST file Dim pstRootFolder As MAPIFolder = namespaceMAPI.Folders(pstDisplayName) ' Loop through all accounts in Outlook For Each account As Account In namespaceMAPI.Accounts Console.WriteLine("Processing account: " & account.DisplayName) ' Access the Inbox folder of the account Dim inboxFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") ' Create a subfolder in the PST file for this account Dim accountFolder As MAPIFolder = pstRootFolder.Folders.Add(account.DisplayName) ' Move emails from the Inbox to the PST subfolder For i As Integer = inboxFolder.Items.Count To 1 Step -1 Try Dim mailItem As MailItem = TryCast(inboxFolder.Items(i), MailItem) If mailItem IsNot Nothing Then mailItem.Move(accountFolder) Console.WriteLine("Moved email: " & mailItem.Subject) End If Catch ex As Exception Console.WriteLine("Error moving email: " & ex.Message) End Try Next Next Console.WriteLine("Emails moved successfully!") End Sub End Module Key Points: Add Reference: Add a reference to the Microsoft.Office.Interop.Outlook library in your project. PST File Path: Replace "C:PathToYourDataFile.pst" with the actual path to your PST file. Permissions: Ensure you have the necessary permissions to access the accounts and move emails. Error Handling: The code includes basic error handling, but you may need to enhance it for production use. Outlook Version: This code is compatible with Outlook versions that support the Interop library. Notes: Running this code may require administrative privileges. Ensure Outlook is properly configured and running on the machine. Test the script in a safe environment before using it on live data to avoid accidental data loss. =============== option ================= ' Initialize Outlook application Dim outlookApp As New Outlook.Application() Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") ' Loop through all accounts For Each account As Outlook.Account In namespaceMAPI.Accounts MsgBox(account.DisplayName) 'Console.WriteLine($"Processing account: {account.DisplayName}") ' Access the Inbox folder for the account Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") ' Specify the target folder (e.g., "Processed Emails") 'Dim targetFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Processed Emails") Next 'Console.WriteLine("Emails moved successfully!") ======= flag status ================== Determining if an email is "flagged" in VB.NET typically refers to checking the follow-up flag status of an email within an application like Microsoft Outlook. This involves interacting with the Outlook object model. Here's a general approach using the Outlook Object Model in VB.NET: Reference the Outlook Library: In your VB.NET project, add a reference to the Microsoft Outlook Object Library. Create an Outlook Application Object: Code Dim olApp As New Outlook.Application() Get the Namespace and Folder. Code Dim olNS As Outlook.Namespace = olApp.GetNamespace("MAPI") Dim inboxFolder As Outlook.MAPIFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) Iterate Through Mail Items. Code For Each item As Object In inboxFolder.Items If TypeOf item Is Outlook.MailItem Then Dim mailItem As Outlook.MailItem = CType(item, Outlook.MailItem) ' Check the FlagStatus property If mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagged Then ' The email is flagged Console.WriteLine($"Email: {mailItem.Subject} is flagged.") ElseIf mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagComplete Then ' The email flag is marked complete Console.WriteLine($"Email: {mailItem.Subject} flag is complete.") Else ' The email is not flagged Console.WriteLine($"Email: {mailItem.Subject} is not flagged.") End If End If Next Explanation: Outlook.OlFlagStatus.olFlagged: Indicates the email has been flagged for follow-up. Outlook.OlFlagStatus.olFlagComplete: Indicates the follow-up flag has been marked as complete. Outlook.OlFlagStatus.olNotFlagged: Indicates no follow-up flag is set. Important Considerations: Outlook Installation: This approach requires Microsoft Outlook to be installed on the machine where the VB.NET application is running. Security Prompts: Outlook may display security prompts when your application attempts to access its data. Error Handling: Implement robust error handling to manage potential issues like Outlook not being open or access denied. Alternatives: For scenarios where Outlook isn't installed or direct interaction is not desired, consider using APIs like Microsoft Graph API (if working with Outlook 365) to access mailbox data and flag status. Vb.net 3 08/02/2025 Vb.net Customizing Control Window State Of App maximize all programs minimize Outlook Mail Cleaner automatically minimize a window in VB.NET, you can set the WindowState property of the form to FormWindowState.Minimized. This can be done in various scenarios, such as when the form loads, in response to a user action (like clicking a button), or based on a timer. 1. Minimizing the Current Form: To minimize the form where the code is executed: Code Me.WindowState = FormWindowState.Minimized This line of code can be placed within an event handler, such as a button click event or a form load event. 2. Minimizing All Active Forms: To minimize all forms currently open in your application: Code For Each frm As Form In Application.OpenForms frm.WindowState = FormWindowState.Minimized Next frm This code iterates through the Application.OpenForms collection and sets the WindowState of each form to Minimized. 3. Minimizing an External Application Window (Advanced): Minimizing an external application's window requires using Windows API functions. This involves obtaining the window handle of the target application and then using functions like ShowWindow to manipulate its state. This is a more complex approach and typically involves PInvoke to call unmanaged code. Example for a specific event: To minimize the form when a specific button is clicked: Code Private Sub btnMinimize_Click(sender As Object, e As EventArgs) Handles btnMinimize.Click Me.WindowState = FormWindowState.Minimized End Sub Maximize all apps Imports System.Runtime.InteropServices Module ModConnection ' Import the ShowWindow function from user32.dll Public Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean End Function ' Constants for ShowWindow Public Const SW_SHOWNORMAL = 1 Public Const SW_SHOWMAXIMIZED = 3 Public Const SW_SHOWMINIMIZED = 6 your function calls Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click File1.Items.Clear() For Each p In Process.GetProcesses If p.MainWindowTitle <> "" Then 'File1.Items.Add(p.MainWindowTitle + "..running") File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]") ShowWindow(p.MainWindowHandle, SW_SHOWMAXIMIZED) End If Next End Sub Vb.net 0 10/19/2025 Vb.net Customizing Control Top Left Width & Height Of Form form top left width height Form Size Public Sub New() ' Set form title Me.Text = "Form Position and Size Example" ' Set form position (Top, Left) and size (Width, Height) Me.StartPosition = FormStartPosition.Manual ' Required to manually set position Me.Left = 200 ' Distance from left edge of screen Me.Top = 150 ' Distance from top edge of screen Me.Width = 800 ' Form width in pixels Me.Height = 600 ' Form height in pixels ' Add a button to display current values Dim btnShowInfo As New Button() btnShowInfo.Text = "Show Form Info" btnShowInfo.Dock = DockStyle.Fill AddHandler btnShowInfo.Click, AddressOf ShowFormInfo Me.Controls.Add(btnShowInfo) End Sub Private Sub ShowFormInfo(sender As Object, e As EventArgs) ' Display current position and size MessageBox.Show( $"Top: {Me.Top}" & vbCrLf & $"Left: {Me.Left}" & vbCrLf & $"Width: {Me.Width}" & vbCrLf & $"Height: {Me.Height}", "Form Info" ) End Sub Public Shared Sub Main() Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) Application.Run(New MainForm()) End Sub End Class MsgBox(My.Computer.Screen.WorkingArea.Height) MsgBox(My.Computer.Screen.WorkingArea.Width) MessageBox.Show( $"Top: {Me.Top}" & vbCrLf & $"Left: {Me.Left}" & vbCrLf & $"Width: {Me.Width}" & vbCrLf & $"Height: {Me.Height}", "Form Info" ) Vb.net 1 11/17/2025 Vb.net Customizing Line Numbers On A Rich Textbox line number textbox Textbox Imports System.Drawing Imports System.Windows.Forms Public Class Form1 Inherits Form Private WithEvents rtb As New RichTextBox() Private WithEvents pnlLineNumbers As New Panel() Public Sub New() ' Form setup Me.Text = "RichTextBox with Line Numbers" Me.Size = New Size(800, 600) ' Panel for line numbers pnlLineNumbers.Dock = DockStyle.Left pnlLineNumbers.Width = 50 pnlLineNumbers.BackColor = Color.LightGray AddHandler pnlLineNumbers.Paint, AddressOf pnlLineNumbers_Paint ' RichTextBox setup rtb.Dock = DockStyle.Fill rtb.Font = New Font("Consolas", 10) rtb.WordWrap = False rtb.ScrollBars = RichTextBoxScrollBars.ForcedBoth ' Add controls Me.Controls.Add(rtb) Me.Controls.Add(pnlLineNumbers) End Sub ' Redraw line numbers when text changes or scrolls Private Sub rtb_TextChanged(sender As Object, e As EventArgs) Handles rtb.TextChanged pnlLineNumbers.Invalidate() End Sub Private Sub rtb_VScroll(sender As Object, e As EventArgs) Handles rtb.VScroll pnlLineNumbers.Invalidate() End Sub ' Draw line numbers Private Sub pnlLineNumbers_Paint(sender As Object, e As PaintEventArgs) e.Graphics.Clear(pnlLineNumbers.BackColor) Dim firstIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, 0)) Dim firstLine As Integer = rtb.GetLineFromCharIndex(firstIndex) Dim lastIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, rtb.Height)) Dim lastLine As Integer = rtb.GetLineFromCharIndex(lastIndex) Dim lineHeight As Integer = TextRenderer.MeasureText("A", rtb.Font).Height Dim y As Integer = 0 For i As Integer = firstLine To lastLine Dim lineNumber As String = (i + 1).ToString() Dim size As Size = TextRenderer.MeasureText(lineNumber, rtb.Font) e.Graphics.DrawString(lineNumber, rtb.Font, Brushes.Black, pnlLineNumbers.Width - size.Width - 5, y) y += lineHeight Next End Sub ' Entry point Public Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class Vb.net 1 12/08/2025 Vb.net Database Create Read Only Recordset create recordset error list box LISTBOX 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 2 09/09/2023 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 0 10/09/2022 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 2 09/09/2023 Vb.net Database Using The Datagridview Control datagrid access mdb view access developer 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 Vb.net 4 02/06/2025 Vb.net Database Creating A Databse Driven Drop Down combo mdb drop down list access developer Module ConnDB() in Using The Datagridview Control Private Sub LoadMultipleCombo() Try sqL = "SELECT [replaceid],[title],[section_code] FROM [mulitreplace] order by [title]" ConnDB() cmd = New OleDbCommand(sqL, conn) 'dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Dim Table_ As String = "mulitreplace ORDER BY title" Dim ds As New DataSet Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) conn.Close() Dim t1 As DataTable = ds.Tables(Table_) txMultiAction.Items.Clear() txMultiAction.ValueMember = "replaceid" txMultiAction.DisplayMember = "title" txMultiAction.DataSource = ds.Tables(Table_) End Sub Function LoadMultiData() ConnDB() Dim Table_ As String = "mulitreplace WHERE replaceid=" + Str(txMultiAction.SelectedValue) Dim query As String = "SELECT * FROM " & Table_ Dim ds As New DataSet Dim cmd As New OleDbCommand(query, conn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) conn.Close() Dim t1 As DataTable = ds.Tables(Table_) Dim row As DataRow Dim Item(2) As String For Each row In t1.Rows Item(0) = row(0) Item(1) = row(1) Item(2) = row(2) Next Return Item(2) End Function Vb.net 2 02/06/2025 Vb.net Database Inserting Records Into Database And Data Grid add insert update sql Web Tools Create & Update Records Imports System.IO Imports System.Text Imports System.Data.OleDb Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click Select Case table_selected Case "copytext" Try sqL = "INSERT INTO [copy_it]([category],[copy_text],[notes]) VALUES ('" + txTitle.Text + "', '" + TXfield3.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, TXfield3.Text, txSectionCode.Text) Case "directorycopy" Try sqL = "INSERT INTO [directory_copy]([prefix],[directory]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text) Case "multireplace" Try sqL = "INSERT INTO [mulitreplace]([title],[section_code]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text) Case "filepaths" Try sqL = "INSERT INTO [file_paths]([file_path],[computer]) VALUES ('" + txSectionCode.Text + "','" + My.Computer.Name + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txSectionCode.Text) Case "emailmoved" Try sqL = "INSERT INTO [move_email]([move_to],[archive],[subject_filter]) VALUES ('" + txTitle.Text + "', '" + TXfield3.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text, TXfield3.Text) Case "emailfiltered" Try sqL = "INSERT INTO [Filtered_email]([importance],[email]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txSectionCode.Text, txTitle.Text) End Select Private Sub btUpdate_Click(sender As Object, e As EventArgs) Handles btUpdate.Click Dim update As DataGridViewRow = DataGridView1.SelectedRows(0) If txReplaceid.Text = "0" Then MsgBox("You cannot edit new records without refresh.") : Exit Sub Select Case table_selected Case "copytext" update.Cells(1).Value = txTitle.Text update.Cells(2).Value = TXfield3.Text update.Cells(3).Value = txSectionCode.Text Try sqL = "UPDATE [copy_it] SET [category]='" + txTitle.Text + "',[copy_text]='" + TXfield3.Text + "',[notes]='" + txSectionCode.Text + "' WHERE [copyID]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Case "multireplace" update.Cells(1).Value = txTitle.Text update.Cells(2).Value = txSectionCode.Text Try sqL = "UPDATE [mulitreplace] SET [title]='" + txTitle.Text + "',[section_code]='" + txSectionCode.Text + "' WHERE [replaceid]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Case "directorycopy" update.Cells(1).Value = txTitle.Text update.Cells(2).Value = txSectionCode.Text Try sqL = "UPDATE [directory_copy] SET [prefix]='" + txTitle.Text + "',[directory]='" + txSectionCode.Text + "' WHERE [directoryID]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Case "filepaths" update.Cells(1).Value = txSectionCode.Text Try sqL = "UPDATE [file_paths] SET [file_path]='" + txSectionCode.Text + "' WHERE [pathID]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Case "emailfiltered" update.Cells(2).Value = txTitle.Text update.Cells(1).Value = txSectionCode.Text Try sqL = "UPDATE [Filtered_email] SET [importance]='" + txTitle.Text + "',[email]='" + txSectionCode.Text + "' WHERE [emailID]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try Case "emailmoved" update.Cells(1).Value = txTitle.Text update.Cells(3).Value = TXfield3.Text update.Cells(2).Value = txSectionCode.Text Try sqL = "UPDATE [move_email] SET [move_to]='" + txTitle.Text + "',[archive]='" + TXfield3.Text + "',[subject_filter]='" + txSectionCode.Text + "' WHERE [moveID]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try End Select Vb.net 2 07/23/2025 Vb.net Database Loading Records From Database Into Data Grid data grid datagrid Web Tools Load Grid With Mdb Imports System.IO Imports System.Text Imports System.Data.OleDb Private Sub btRefresh_Click(sender As Object, e As EventArgs) Handles btRefresh.Click txReplaceid.Text = "" : txTitle.Text = "" : txSectionCode.Text = "" : DataGridView1.Columns.Clear() Select Case table_selected Case "copytext" txSectionCode.Height = 100 : TXfield3.Visible = True : txTitle.Visible = True With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("copyID", "copyID") : .Columns.Add("category", "category") : .Columns.Add("copy_text", "copy_text") : .Columns.Add("notes", "notes") .Columns(0).Visible = False .Columns(1).HeaderText = "Category" : .Columns(1).Width = 120 .Columns(2).HeaderText = "TEXT" : .Columns(2).Width = 420 .Columns(3).HeaderText = "Notes" : .Columns(3).Width = 200 Try sqL = "SELECT [copyID],[category],[copy_text],[notes] FROM [copy_it] ORDER BY [category],[copy_text]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2), dr(3)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With Case "filepaths" txSectionCode.Height = 100 : TXfield3.Visible = False With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("pathID", "pathID") : .Columns.Add("file_path", "file_path") .Columns(0).Visible = False : txTitle.Visible = False .Columns(1).HeaderText = "File Path" .Columns(1).Width = 1200 Try sqL = "SELECT [pathID],[file_path] FROM [file_paths] WHERE [computer]='" + My.Computer.Name + "' ORDER BY [file_path]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With Case "multireplace" txSectionCode.Height = 300 : TXfield3.Visible = False With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("switchid", "switchid") : .Columns.Add("position", "Position") : .Columns.Add("code", "code") : .Columns.Add("Description", "Description") .Columns(0).Visible = False : txTitle.Visible = True .Columns(1).HeaderText = "Title" .Columns(2).HeaderText = "Code" .Columns(1).Width = 300 : .Columns(2).Width = 1200 Try sqL = "SELECT [replaceid],[title],[section_code] FROM [mulitreplace] order by [title]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With Case "directorycopy" txSectionCode.Height = 300 : TXfield3.Visible = False With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("directorid", "DirectoryID") : .Columns.Add("prefix", "Prefix") : .Columns.Add("directory", "Directory") ' .Columns.Add("Description", "Description") .Columns(0).Visible = False : txTitle.Visible = True .Columns(1).HeaderText = "Prefix" .Columns(2).HeaderText = "Directory" .Columns(1).Width = 300 : .Columns(2).Width = 1200 Try sqL = "SELECT [directoryID],[prefix],[directory] FROM [directory_copy] order by [prefix]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With Case "emailfiltered" txSectionCode.Height = 100 : TXfield3.Visible = False With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("emailID", "ID") : .Columns.Add("email", "Email Filter") : .Columns.Add("importance", "Rate") ' .Columns.Add("Description", "Description") .Columns(0).Visible = False : txTitle.Visible = True .Columns(1).HeaderText = "Email Filter" .Columns(2).HeaderText = "Rated" .Columns(1).Width = 400 : .Columns(2).Width = 100 Try sqL = "SELECT [emailID],[email],[importance] FROM [Filtered_email] ORDER BY [email]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With Case "emailmoved" txSectionCode.Height = 100 : TXfield3.Visible = True : txTitle.Visible = True With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("moveID", "ID") : .Columns.Add("move_to", "Move To") : .Columns.Add("subject_filter", "Subject Phrase") : .Columns.Add("archive", "Archive") .Columns(0).Visible = False .Columns(1).HeaderText = "Move To" : .Columns(1).Width = 250 .Columns(2).HeaderText = "Subject Phrase" : .Columns(2).Width = 600 .Columns(3).HeaderText = "Archive" : .Columns(3).Width = 200 Try sqL = "SELECT [moveID],[move_to],[subject_filter],[archive] FROM [move_email] ORDER BY [move_to],[subject_filter]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2), dr(3)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With End Select End Sub =============== mouse event ============== Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0) Select Case table_selected Case "copytext" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txTitle.Text = dr.Cells(1).Value.ToString() TXfield3.Text = dr.Cells(2).Value.ToString() Clipboard.SetText(TXfield3.Text, TextDataFormat.UnicodeText) txSectionCode.Text = dr.Cells(3).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try Case "directorycopy" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txTitle.Text = dr.Cells(1).Value.ToString() txSectionCode.Text = dr.Cells(2).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try Case "multireplace" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txTitle.Text = dr.Cells(1).Value.ToString() txSectionCode.Text = dr.Cells(2).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try Case "filepaths" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txSectionCode.Text = dr.Cells(1).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try Case "emailmoved" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txTitle.Text = dr.Cells(1).Value.ToString() TXfield3.Text = dr.Cells(3).Value.ToString() txSectionCode.Text = dr.Cells(2).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try Case "emailfiltered" Try txReplaceid.Text = dr.Cells(0).Value.ToString() txSectionCode.Text = dr.Cells(1).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try End Select End Sub Vb.net 4 09/08/2025 Vb.net Database ConnectionMod.vb add update sql access radio Web Tools Database Imports System.Data.OleDb Module ModConnection Public cur As Form Public dt As DataTable Public conn As OleDbConnection Public cmd As OleDbCommand Public dr As OleDbDataReader Public da As OleDbDataAdapter Public ds As DataSet Public sqL As String Public Sub ConnDB() Dim R As String = My.Computer.Name ' R = GetIni("Database", R, INI) If R = "" Then WriteIni("Database", My.Computer.Name, "Dropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI) Shell("write.exe " + INI, vbNormalFocus) : Exit Sub End If 'C:UserssteveDropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb" Try Dim connectionString As String = "Provider=Microsoft.jet.oledb.4.0;Data Source=" + R 'Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + R conn = New OleDbConnection(connectionString) 'conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath() & "beer.mdb;") 'conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Databasephone.mdb;Jet OLEDB:Database Password = escobar;") conn.Open() Catch ex As Exception MsgBox("Failed in Connecting to database") End Try End Sub Public Function getDataTable(ByVal SQL As String) As DataTable ConnDB() Dim cmd As New OleDbCommand(SQL, conn) Dim dt As New DataTable Dim da As New OleDbDataAdapter(cmd) da.Fill(dt) Return dt End Function End Module -------------- radio button test ------------------------- Private Sub rbFilePaths_CheckedChanged(sender As Object, e As EventArgs) Handles rbFilePaths.CheckedChanged If rbFilePaths.Checked = True Then table_selected = "filepaths" : btRefresh_Click(sender, e) End Sub Private Sub rbMultireplace_CheckedChanged(sender As Object, e As EventArgs) Handles rbMultireplace.CheckedChanged If rbMultireplace.Checked = True Then table_selected = "multireplace" : btRefresh_Click(sender, e) End Sub Private Sub txText_TextChanged(sender As Object, e As EventArgs) Handles txText.TextChanged End Sub Private Sub rbDirectoryCopy_CheckedChanged(sender As Object, e As EventArgs) Handles rbDirectoryCopy.CheckedChanged If rbDirectoryCopy.Checked = True Then table_selected = "directorycopy" : btRefresh_Click(sender, e) End Sub Private Sub RBcopyText_CheckedChanged(sender As Object, e As EventArgs) Handles RBcopyText.CheckedChanged If RBcopyText.Checked = True Then table_selected = "copytext" : btRefresh_Click(sender, e) End Sub Private Sub RBemailFiltered_CheckedChanged(sender As Object, e As EventArgs) Handles RBemailFiltered.CheckedChanged If RBemailFiltered.Checked = True Then table_selected = "emailfiltered" : btRefresh_Click(sender, e) End Sub Private Sub RBemailMove_CheckedChanged(sender As Object, e As EventArgs) Handles RBemailMove.CheckedChanged If RBemailMove.Checked = True Then table_selected = "emailmoved" : btRefresh_Click(sender, e) End Sub ====== selected table ============= Select Case table_selected Case "copytext" Case "directorycopy" Case "multireplace" Case "filepaths" Case "emailmoved" Case "emailfiltered" End Select Vb.net 5 07/23/2025 Vb.net Files Directory Files Into A List Box Checking Drive Available delete files directory drive listbox 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 2 09/09/2023 Vb.net Files Read And Write ENTIRE FILE open read file write file entire File Writing [READ] read entire file into string. A = My.Computer.FileSystem.ReadAllText(Path.TREE2 + "/" + Explore.File1.Items(J).ToString, System.Text.Encoding.Default) CODE1 = My.Computer.FileSystem.ReadAllText(Tree2 + Filename + "Code.txx") [WRITE] Dim CODE1 As String = My.Computer.FileSystem.ReadAllText(Tree2 + Filename + "Code.txx") J = InStr(CODE1, "``") : CODE1 = Left(CODE1, J - 1) For J = 0 To TMPA.Count - 1 If InStr(CODE1, "`" + TMPA(J) + "`") = 0 Then NotFound = True : CODE1 = CODE1 + "`" + TMPA(J) + "`" + vbCR Next CODE1 = CODE1 + "``" + vbCR If NotFound = True Then My.Computer.FileSystem.WriteAllText(Tree2 + Filename + "Code.txx", CODE1, append:=False) Vb.net 1290 09/09/2023 Vb.net Files Read Text File Line By Line & Write read file line write append Imports Microsoft.VisualBasic Module Module1 Sub Main() Dim filePath As String = "example.txt" Dim fileNumber As Integer = FreeFile() Try ' Open file for append using legacy VB method FileOpen(fileNumber, filePath, OpenMode.Append) 'FileOpen(7, TREE3 + FLD(0, 0) + "_header.php", OpenMode.Output) PrintLine(fileNumber, "This is a new line of text.") Catch ex As Exception Console.WriteLine("Error: " & ex.Message) Finally FileClose(fileNumber) End Try End Sub End Module READ LINES FROM A TEXT FILE Dim LineInput As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(Tree + "tabletempsave.txt") Do Until LineInput.EndOfStream A = LineInput.ReadLine : A = Trim(A) LOOP lineInput.close ========================================= Shared Sub Main() ' Get an available file number. Dim file_num As Integer = FreeFile() ' Open the file. Dim file_name As String = "test.txt" FileOpen(file_num, file_name, OpenMode.Input, OpenAccess.Read, OpenShare.Shared) ' Read the file's lines. Do While Not EOF(file_num) ' Read a line. Dim txt As String = LineInput(file_num) Console.WriteLine(txt) Loop ' Close the file. FileClose(file_num) End Sub Vb.net 1352 09/09/2023 Vb.net Files Strip Html From Text strip html strip tags browser If you get html text from a browser you can read the clipboard as html Imports System.Text.RegularExpressions Module Module1 Sub Main() ' Input. Dim html As String = "There was a .NET programmer " + "and he stripped the HTML tags." ' Call Function. Dim tagless As String = StripTags(html) ' Write. Console.WriteLine(tagless) End Sub ''' ''' Strip HTML tags. ''' Function StripTags(ByVal html As String) As String ' Remove HTML tags. Return Regex.Replace(html, "<.*?>", "") End Function End Module Vb.net 1009 09/09/2023 Vb.net Files Create A Copy Or Move A File In A Different Directory copy files move files File Management ' Copy the file to a new location without overwriting existing file. My.Computer.FileSystem.CopyFile( "C:UserFilesTestFilestestFile.txt", "C:UserFilesTestFiles2testFile.txt") ' Copy the file to a new folder, overwriting existing file. My.Computer.FileSystem.CopyFile( "C:UserFilesTestFilestestFile.txt", "C:UserFilesTestFiles2testFile.txt", Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing) ' Copy the file to a new folder and rename it. My.Computer.FileSystem.CopyFile( "C:UserFilesTestFilestestFile.txt", "C:UserFilesTestFiles2NewFile.txt", Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing) ================== overwrite defaults to false need to add ",true" inside the function The My.Computer.FileSystem.MoveFile method can be used to move a file to another folder. If the target structure does not exist, it will be created. To move a file Use the MoveFile method to move the file, specifying the file name and location for both the source file and the target file. This example moves the file named test.txt from TestDir1 to TestDir2. Note that the target file name is specified even though it is the same as the source file name. VB Copy My.Computer.FileSystem.MoveFile("C:TestDir1test.txt", "C:TestDir2test.txt") To move a file and rename it Use the MoveFile method to move the file, specifying the source file name and location, the target location, and the new name at the target location. This example moves the file named test.txt from TestDir1 to TestDir2 and renames it nexttest.txt. VB Copy My.Computer.FileSystem.MoveFile("C:TestDir1test.txt", "C:TestDir2nexttest.txt", FileIO.UIOption.AllDialogs, FileIO.UICancelOption.ThrowException) Vb.net 0 12/10/2023 Vb.net Files FILE MODIFICATION file date newer File Copy 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 0 11/17/2024 Vb.net Files File Drag Drop Listview drag drop file 3rd party Developer 12/31/25 ai search To programmatically drag multiple files from your VB.NET application and drop them onto a third-party application, you must prepare a DataObject in a standard format that other Windows programs can understand. The standard format for files is DataFormats.FileDrop. Initiating the Drag Operation In your VB.NET application, for the control you want to initiate the drag from (e.g., a Button or a ListView item), use the DoDragDrop method within a mouse event (like MouseDown): vb.net WEBTOOLS USING File1 control Private Sub File1_MouseDown(sender As Object, e As MouseEventArgs) Handles File1.MouseDown ' Create a StringCollection to hold the paths of the files you want to drag. Dim filePaths As New System.Collections.Specialized.StringCollection ' Add the full, qualified paths of the files to the collection. ' This example uses a single file for brevity; you can add multiple paths here. For Each Item As String In File1.SelectedItems Try filePaths.Add(Path.TREE2 + "" + Item.ToString) Catch ex As Exception Continue For End Try Next 'filePaths.Add(Path.Combine(Application.StartupPath, "TestData1.txt")) 'filePaths.Add(Path.Combine(Application.StartupPath, "TestData2.txt")) ' ... add all other file paths ... ' Create a DataObject and set the FileDrop list. Dim data As New DataObject() data.SetFileDropList(filePaths) ' Initiate the drag-and-drop operation, allowing "Copy" or "All" effects. ' Using DragDropEffects.Copy is standard for file drag-and-drop between apps. File1.DoDragDrop(data, DragDropEffects.Copy) End Sub =========== Imports System.IO Imports System.Windows.Forms Public Class Form1 Private originalSelection As List(Of Integer) Public Sub New() InitializeComponent() ' Example setup ListBox1.SelectionMode = SelectionMode.MultiExtended ListBox1.AllowDrop = False ' We are dragging out, not in ' Add some example file paths ListBox1.Items.Add("C:TempFile1.txt") ListBox1.Items.Add("C:TempFile2.txt") ListBox1.Items.Add("C:TempFile3.txt") End Sub ' Capture selection before mouse down Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown originalSelection = New List(Of Integer)(ListBox1.SelectedIndices.Cast(Of Integer)()) End Sub ' Start drag without losing selection Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove If e.Button = MouseButtons.Left AndAlso originalSelection IsNot Nothing AndAlso originalSelection.Count > 0 Then ' Restore original selection in case it changed ListBox1.ClearSelected() For Each idx In originalSelection ListBox1.SelectedIndices.Add(idx) Next ' Prepare file drop list Dim files As New List(Of String) For Each idx In originalSelection Dim path As String = ListBox1.Items(idx).ToString() If File.Exists(path) Then files.Add(path) End If Next If files.Count > 0 Then Dim data As New DataObject(DataFormats.FileDrop, files.ToArray()) ListBox1.DoDragDrop(data, DragDropEffects.Copy) End If End If End Sub End Class =========== Compatibility with Third-Party Applications When dragging between different applications, you must use the standard Windows drag-and-drop formats (like DataFormats.FileDrop). Most third-party applications that support receiving files via drag-and-drop will be listening for this standard format in their own DragEnter and DragDrop event handlers. The crucial step is creating a DataObject and using SetFileDropList() to ensure the data is provided in a standard, interoperable format. The third-party application must have its AllowDrop property set to True for the target control to accept drops. Some older or specific third-party applications might expect different data formats (like a MemoryStream or specific custom formats), but the file path array is the most common and widely supported method. For more information on programmatically simulating a drop to a third-party application without a user's manual mouse action (which is complex and often requires Windows API calls), refer to resources on programmatic drag-and-drop on Microsoft Learn. o programmatically drag a file from your VB.NET application and drop it onto a third-party application, you need to initiate a standard OLE drag-and-drop operation from your VB.NET application. The third-party application, if built to accept standard Windows file drops (like Windows Explorer or Notepad), will handle the drop automatically. Step-by-Step Implementation The key is to create a DataObject containing the file path(s) in the DataFormats.FileDrop format and then call the DoDragDrop method. 1. Set up the UI (e.g., a Button or a ListView) You'll need a control in your application from which the drag operation will start. A Button or ListView item's MouseDown event is a good place to initiate this. 2. Implement the MouseDown event In the MouseDown event of your source control, you will: Specify the full path of the file(s) you want to drag. Create a DataObject. Set the data using DataFormats.FileDrop. Call DoDragDrop to start the operation. Here is a VB.NET code snippet (for Windows Forms) that initiates a drag operation with a single file: vb.net Imports System.IO Imports System.Collections.Specialized ' Required for StringCollection Private Sub YourControl_MouseDown(sender As Object, e As MouseEventArgs) Handles YourControl.MouseDown ' Only start the drag if the left mouse button is pressed If e.Button = Windows.Forms.MouseButtons.Left Then ' Define the path(s) to the file(s) you want to drag. ' Use StringCollection for multiple files, or a String array for one or more. Dim filePaths As New StringCollection() ' Example: Add a specific file from your application's startup path Dim filePath As String = Path.Combine(Application.StartupPath, "YourFileName.txt") ' Ensure the file exists before attempting to drag it If File.Exists(filePath) Then filePaths.Add(filePath) ' Create a DataObject and set the file drop list Dim data As New DataObject() data.SetFileDropList(filePaths) ' Start the drag-and-drop operation, allowing Copy effects Me.DoDragDrop(data, DragDropEffects.Copy) Else MessageBox.Show("File not found: " & filePath) End If End If End Sub Considerations for Third-Party Applications Standard Formats: By using DataFormats.FileDrop and a StringCollection of paths, your application adheres to the standard Windows OLE drag-and-drop contract, ensuring compatibility with most third-party applications that support file drops (e.g., Windows Explorer, email clients, specific document management systems). Permissions (UIPI): Be aware of User Interface Privilege Isolation (UIPI). If your VB.NET application is running with Administrator privileges, it will not be able to drag and drop files into a third-party application running as a standard (non-administrator) user (e.g., dragging from an elevated Visual Studio instance to a normal Windows Explorer window). If this is an issue, run both applications at the same privilege level. Programmatic Drop (Advanced): If the target application does not support standard drag-and-drop or you need to automate the "drop" part of the process without user interaction (e.g., navigating to a specific folder within the target app first), this becomes significantly more complex, often requiring Windows API calls (SendMessage, WM_DROPFILES) or UI automation tools, which are beyond basic drag-and-drop functionality. The simple DoDragDrop method handles the initiation of the drag, but the target controls the drop Re: Need help dragging File FROM ListView to Explorer (and other places) Use the listview mousedown event. If the left button is held down and you have files selected, use Code: listviewname.dodragdrop(dataformats.filedrop, new string() {“file1.ext”, etc}) The dataformats and the string array of filenames are the important parts. Windows explorer will recognise your files. All of your previous code was what you’d use to enable dropping in your listview. You might want to keep your listview’s allowdrop property, and handle dragover, so you can see that something is being dragged above your listview. Don’t handle the dragdrop event if you don’t want files dropped in your listview ================================= Private Sub ListView1_DragDrop1(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListView1.DragDrop If e.Data.GetDataPresent(DataFormats.FileDrop) Then Dim MyFiles() As String Dim i As Integer ' Assign the files to an array. MyFiles = e.Data.GetData(DataFormats.FileDrop) ' Loop through the array and add the files to the list. For i = 0 To MyFiles.Length - 1 Dim lvitem As New ListViewItem lvitem.Text = System.IO.Path.GetFileNameWithoutExtension(MyFiles(i)) 'File Name "Notepad" lvitem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(MyFiles(i)).Extension) 'Just the extension, soon to be type lvitem.SubItems.Add(((My.Computer.FileSystem.GetFileInfo(MyFiles(i)).Length) / 1000) & " KB") 'File Size e.g. "2,400KB" lvitem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(MyFiles(i)).DirectoryName) 'Path ListView1.Items.Add(lvitem) Next End If End Sub 3rd party To programmatically simulate a drag-and-drop operation in VB.NET, where files are dropped into a third-party application, you can use the DoDragDrop method in combination with the Windows API for more advanced scenarios. Below is an example of how you can achieve this: Example: Drag and Drop Files to a Third-Party Application Imports System.Runtime.InteropServices Imports System.Windows.Forms Public Class DragDropHelper Private Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr End Function Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr End Function Private Const WM_DROPFILES As Integer = &H233 Public Shared Sub DragAndDropFile(filePath As String, targetWindowTitle As String) ' Find the target window by its title Dim targetWindowHandle As IntPtr = FindWindow(Nothing, targetWindowTitle) If targetWindowHandle = IntPtr.Zero Then MessageBox.Show("Target application window not found.") Return End If ' Create a DataObject containing the file path Dim dataObject As New DataObject(DataFormats.FileDrop, New String() {filePath}) ' Simulate the drag-and-drop operation Clipboard.SetDataObject(dataObject, True) SendMessage(targetWindowHandle, WM_DROPFILES, IntPtr.Zero, IntPtr.Zero) End Sub End Class Another example using file explorer Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown Dim data As New DataObject() Dim filePaths As New StringCollection filePaths.Add(Path.Combine(Application.StartupPath, "TestData.txt")) data.SetFileDropList(filePaths) DoDragDrop(data, DragDropEffects.Copy) End Sub Vb.net 1 01/03/2026 Vb.net Formatting Replacing Text In A String replace trim Replacing Dim APOS2 As Integer, APOS As Integer A = Replace(A, Chr(9), " ") APOS2 = Len(A) : APOS = Len(LTrim$(A)) : APOS = APOS2 - APOS A = Trim$(A) A = Replace(A, Chr(34), Chr(34) + "+chr(34)+" + Chr(34)) Vb.net 0 01/13/2025 Vb.net Formatting Sort Files By Date delete sort listbox list box date files selected Webtools File Management Remove unwanted items always LOOP BACKWARDS ' Define the unwanted text Dim unwantedText As String = "Unwanted Item Text" ' Loop backwards from the last item to the first (ListBox.Items is 0-based) For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1 ' Check if the current item matches the unwanted text If ListBox1.Items(i).ToString() = unwantedText Then ' If it matches, remove the item at the current index ListBox1.Items.RemoveAt(i) End If Next 'PRINT CONTENT TO VIEW DIM B AS string For i As Integer = 0 to ListBox1.Items.Count - 1 B=B + ListBox1.Items(i).ToString()+VBCRLF Next table.text=B 'PRINT SELECTED CONTENT TO VIEW If ListBox1.SelectedItems.Count > 0 Then MessageBox.Show("Processing " & ListBox1.SelectedItems.Count.ToString() & " items.") ' Loop through each selected item in the collection For Each selectedItem As Object In ListBox1.SelectedItems ' You can cast the item to a specific type if needed (e.g., String) Dim itemText As String = selectedItem.ToString() ' Perform your processing logic here Debug.WriteLine("Processing item: " & itemText) ' Example: add to another listbox ' ListBox2.Items.Add(itemText) Next ' Optional: Clear the selection after processing ' ListBox1.ClearSelected() Else MessageBox.Show("No items selected.") End If webtools Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btDateSort.Click Dim J As Integer, N As Integer = 0, N2 As Integer = 0 Dim DateFile As Array = Directory.GetFiles(Path.TREE2).OrderBy(Function(d) New FileInfo(d).CreationTime).ToArray File1.Items.Clear() N = DateFile(J).LastIndexOf("") For J = 0 To DateFile.Length - 1 N2 = DateFile(J).length - N - 1 File1.Items.Add(DateFile(J).substring(N + 1, N2)) Next End Sub StrFilesArray=Directory.GetFiles(DirectoryPath).OrderBy(Function(d) New FileInfo(d).CreationTime).ToArray Dim name As String Dim list As List(of DateTime) = new List(of DateTime) For Each file As String In System.IO.Directory.GetFiles(directoryPath) name = System.IO.Path.GetFileNameWithoutExtension(file) list.Add(Datetime.ParseExact(name, "dd-MM-yyyy", CultureInfo.InvariantCulture)) Next list.Sort(New Comparison(Of Date)(Function(x As Date, y As Date) y.CompareTo(x))) ComboBox1.DataSource = list Vb.net 3 01/25/2026 Vb.net Function Populating The Treeview List treeview files directory Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PopulateTreeView(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) End Sub Private Sub PopulateTreeView(path As String) ' Clear the TreeView control TreeView1.Nodes.Clear() ' Create the root node for the TreeView Dim rootNode = New TreeNode(path) With {.Tag = path} TreeView1.Nodes.Add(rootNode) ' Recursively add child nodes for directories and their files AddDirectories(rootNode) End Sub Private Sub AddDirectories(parentNode As TreeNode) ' Get the path of the parent node Dim path = DirectCast(parentNode.Tag, String) ' Get the directories in the current path Dim directories = IO.Directory.GetDirectories(path) ' Add child nodes for each directory For Each dir As String In directories Dim directoryNode = New TreeNode(IO.Path.GetFileName(dir)) With {.Tag = dir} parentNode.Nodes.Add(directoryNode) Try ' Get the files in the current directory Dim files = IO.Directory.GetFiles(dir) ' Add child nodes for each file For Each file In files Dim fileNode = New TreeNode(IO.Path.GetFileName(file)) With {.Tag = file} directoryNode.Nodes.Add(fileNode) Next ' Recursively add child nodes for subdirectories AddDirectories(directoryNode) Catch invalidAccessEx As UnauthorizedAccessException directoryNode.ForeColor = Color.Red End Try Next End Sub Vb.net 1 12/27/2023 Vb.net Function Outlook Email outlook move email OUTLOOK 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 Vb.net 4 07/21/2025 Vb.net Function Calling A Click Event call Vb.net Events Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Button2_Click(Sender, e) End Sub BTbulkMove_Click(sender As Object, e As EventArgs) translates to BTbulkMove_Click(sender, e) BTtest_Click(sender As Object, e As EventArgs) translates to BTtest_Click(sender, e) Vb.net 0 08/21/2025 Vb.net Function Function Variable Passing function Function Key Points: ByVal passes a copy of the variable. Changes inside the function do not modify the original variable. This is the default passing mechanism in VB.NET if you don’t specify ByRef. When to use ByVal When you want to protect the original variable from being changed. When passing immutable data (e.g., numbers, strings) where modification is unnecessary. If you want, I can also show you the ByRef version so you can compare how it changes the original variable Function EmailCriteria(ByRef email_count As Int16) Dim MV(200, 2) As String, L As Integer Try Dim sqL As String = "SELECT [move_to],[subject_filter],[archive] FROM [move_email] WHERE [archive]>0 ORDER BY [move_to],[subject_filter]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception LAerrorMessage.Text = "error BTbulkMove DB:" & ex.Message End Try Do While dr.Read MV(L, 0) = dr(0) : MV(L, 1) = dr(1) : MV(L, 2) = dr(2) L = L + 1 Loop email_count = L - 1 Return MV End Function Vb.net 0 02/28/2026 Vb.net Ini Read And Write From Ini File ini windows API api 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 3 11/17/2025 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 1205 08/05/2024 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 2 09/09/2023 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 0 01/01/2024 Vb.net Setup How To: Change The Default Location For Projects Default Location Projects folder How to: Change the Default Location for Projects Visual Studio 2010 Other Versions 13 out of 21 rated this helpful - Rate this topic You can change the path where new projects and files are created by using the Options dialog box. Your existing projects remain in their current location. Web-related projects, such as XML Web services and ASP.NET Web applications, are not affected by this setting. The default Web server is based on the most recently used server. To change the default save location On the Tools menu, select Options. From the Projects and Solutions folder, select General. In the Visual Studio projects location text box, enter a location for files and projects. Vb.net 1850 09/09/2023 Vb.net Setup Have Application Run In The Background application background process file explorer http://www.dreamincode.net/forums/topic/59527-make-a-program-to-run-in-the-background/ This tutorial deals with how to make a standard VB.NET application run in the background, like a process. By background i mean that the application will have no interface (form or console) and will run from a Sub Main(), but will not terminate once all the code in Main has executed. That means your program will run like a normal form application, and will only exit when told to. First, create a standard Windows Form application. Then, go to the solution explorer, and double click on the item that says My Project. [attachment=7480:attachment] Once that is opened, you should see something like this [attachment=7484:attachment] There are a few very simple things you need to change there. First, uncheck the box that says "Enable Application Framework". Then, go to the box that says "Startup Object:" and change that to Sub Main. Then, delete the form that was put in your application automatically. By now, you should notice that there is no startup object in your application. In fact, there is no Code in your application. So, you need to add a Sub Main in. Add a new module to your application (call it anything you want). Then, add this sub into your module: 1Sub Main()2 'This will execute when your 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 1215 09/09/2023 Vb.net Setup Compiling Error Locations errors optimization Locating Bug Fixes optimize error Project- project properties (located towards bottom) Compile -towards bottom "Advanced Compile Options" uncheck "Enable Optimizations" ============ Resolving the 'Microsoft.Jet.OLEDB.4.0' Provider Not Registered Er… 1 2 3 The error Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine typically occurs when you try to use the Microsoft Jet OLEDB 4.0 driver on a 64-bit operating system. This driver is not compatible with 64-bit systems, leading to this error. Example string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Perform database operations } Solution 1: Change Project Build Configuration One common solution is to change the build configuration of your project to target x86 (32-bit) instead of Any CPU or x64. Steps: Open your project in Visual Studio. Go to Project Properties > Build. Change the Platform target to x86. Rebuild your project. Solution 2: Use Microsoft.ACE.OLEDB.12.0 Another solution is to use the Microsoft Access Database Engine, which provides a 64-bit compatible driver. Example: string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabase.accdb;"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Perform database operations } Solution 3: Enable 32-bit Applications in IIS If you are running a web application, you can enable 32-bit applications in IIS 3 . Steps: Open IIS Manager. Select the application pool your application is using. Click on Advanced Settings. Set Enable 32-Bit Applications to True. By following these steps, you can resolve the Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine error and ensure your application runs smoothly on both 32-bit and 64-bit systems. Learn more: 1 - stackoverflow.com 2 - answers.microsoft.com 3 - stackoverflow.com Resolving the 'Microsoft.Jet.OLEDB.4.0' Provider Not Registered Er… 1 2 3 The error Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine typically occurs when you try to use the Microsoft Jet OLEDB 4.0 driver on a 64-bit operating system. This driver is not compatible with 64-bit systems, leading to this error. Example string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Perform database operations } Solution 1: Change Project Build Configuration One common solution is to change the build configuration of your project to target x86 (32-bit) instead of Any CPU or x64. Steps: Open your project in Visual Studio. Go to Project Properties > Build. Change the Platform target to x86. Rebuild your project. Solution 2: Use Microsoft.ACE.OLEDB.12.0 Another solution is to use the Microsoft Access Database Engine, which provides a 64-bit compatible driver. Example: string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabase.accdb;"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); // Perform database operations } Solution 3: Enable 32-bit Applications in IIS If you are running a web application, you can enable 32-bit applications in IIS 3 . Steps: Open IIS Manager. Select the application pool your application is using. Click on Advanced Settings. Set Enable 32-Bit Applications to True. By following these steps, you can resolve the Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine error and ensure your application runs smoothly on both 32-bit and 64-bit systems. Learn more: 1 - stackoverflow.com 2 - answers.microsoft.com 3 - stackoverflow.com Vb.net 0 07/23/2025 Vb.net String String Functions substring [CHAR] '// see indexof also Dim myString As String = "ABCDE" Dim myChar As Char myChar = myString.Chars(3) '//myChar = "D" [CONCAT] Dim aString As String = "A" Dim bString As String = "B" Dim cString As String = "C" Dim dString As String = "D" Dim myString As String ' myString = "ABCD" myString = String.Concat(aString, bString, cString, dString) [INDEXOF] '// see char also Dim myString As String = "ABCDE" Dim myInteger As Integer myInteger = myString.IndexOf("D") ' myInteger = 3 [instr] [left] [LENGTH] Dim MyString As String = "This is my string" Dim stringLength As Integer ' Explicitly set the string to Nothing. MyString = Nothing ' stringLength = 0 stringLength = Len(MyString) ' This line, however, causes an exception to be thrown. stringLength = MyString.Length [MID] '//see substring. first charcter is position 1 Dim aString As String = "SomeString" Dim bString As String bString = Mid(aString, 3, 3) [right] [SPLIT] '// returns an array Dim shoppingList As String = "Milk,Eggs,Bread" Dim shoppingItem(2) As String shoppingItem = shoppingList.Split(","c) [SUBSTRING] '//first character is position zero. See mid() Dim aString As String = "A String" Dim bString As String bString = aString.SubString(2,6) '//bString = "String" or Dim aString As String = "Left Center Right" Dim subString As String ' subString = "Center" subString = aString.SubString(5,6) Visual Basic .NET methods are used as inherent functions of the language. They may be used without qualification in your code. The following example shows typical use of a Visual Basic .NET string-manipulation command: In this example, the Mid function performs a direct operation on aString and assigns the value to bString. You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods and instance methods. A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example: Dim aString As String bString = String.Copy("A literal string") In the preceding example, the String.Copy method is a static method, which acts upon an expression it is given and assigns the resulting value to bString. NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing. Comparing Strings You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class. In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used: Dim myString As String = "Alphabetical" Dim secondString As String = "Order" Dim result As Integer result = String.Compare (myString, secondString) This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than a null reference. Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into account, and to compare substrings within the supplied strings. For more information on how to compare strings, see String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method. Searching for Strings Within Your Strings There are times when it is useful to have data about the characters in your string and the positions of those characters within your string. A string can be thought of as an array of characters (Char instances); you can retrieve a particular character by referencing the index of that character through the Chars property. For example: You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following example: Dim myString As String = "ABCDE" Dim myInteger As Integer myInteger = myString.IndexOf("D") ' myInteger = 3 In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can also use the String.LastIndexOf Method to search for the last occurrence of a character in your string. Creating New Strings from Old When using strings, you may want to modify your strings and create new ones. You may want to do something as simple as convert the entire string to uppercase, or trim off trailing spaces; or you may want to do something more complex, such as extracting a substring from your string. The System.String class provides a wide range of options for modifying, manipulating, and making new strings out of your old ones. To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows: You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below: Dim myString As String = "UpPeR oR LoWeR cAsE" Dim newString As String ' newString = "UPPER OR LOWER CASE" newString = UCase(myString) ' newString = "upper or lower case" newString = LCase(myString) ' newString = "UPPER OR LOWER CASE" newString = myString.ToUpper ' newString = "upper or lower case" newString = myString.ToLower The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a given string. For information on these commands, see Format Function or String.Format Method. You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the Visual Basic .NET Trim function. An example is shown: Dim spaceString As String = _ " This string will have the spaces removed " Dim oneString As String Dim twoString As String ' This removes all trailing and leading spaces. oneString = spaceString.Trim ' This also removes all trailing and leading spaces. twoString = Trim(spaceString) If you only want to remove trailing spaces, you can use the String.TrimEnd Method or the RTrim function, and for leading spaces you can use the String.TrimStart Method or the LTrim function. For more details, see LTrim, RTrim, and Trim Functions functions. The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your string. The following example trims all leading and trailing instances of the "#" character: Dim myString As String = "#####Remove those!######" Dim oneString As String OneString = myString.Trim("#") You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method. If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can replace them with another character using the String.Replace Method. For example: Dim aString As String = "This is My Str@o@o@ing" Dim myString As String Dim anotherString As String ' myString = "This is My String" myString = aString.Remove(14, 5) ' anotherString = "This is Another String" anotherString = myString.Replace("My", "Another") You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid Statement can also be used to replace an interior string with another string. You can also use the String.Insert Method to insert a string within another string, as in the following example: Dim aString As String = "This is My Stng" Dim myString As String ' Results in a value of "This is My String". myString = aString.Insert(13, "ri") The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the second parameter is the string to be inserted. You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example: Dim shoppingItem(2) As String Dim shoppingList As String shoppingItem(0) = "Milk" shoppingItem(1) = "Eggs" shoppingItem(2) = "Bread" shoppingList = String.Join(",", shoppingItem) The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the method still adds a separator string between all the empty instances in your array. You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c. The Visual Basic .NET Mid Function can be used to generate substrings of your string. The following example shows this functions in use: Dim aString As String = "Left Center Right" Dim rString, lString, mString As String ' rString = "Right" rString = Mid(aString, 13) ' lString = "Left" lString = Mid(aString, 1, 4) ' mString = "Center" mString = Mid(aString, 6,6) Substrings of your string can also be generated using the String.Substring Method. This method takes two arguments: the character index where the substring is to start, and the length of the substring. The String.Substring method operates much like the Mid function. An example is shown below: There is one very important difference between the String.SubString method and the Mid function. The Mid function takes an argument that indicates the character position for the substring to start, starting with position 1. The String.SubString method takes an index of the character in the string at which the substring is to start, starting with position 0. Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use with the Mid function, but 0,1,2,3,4 for use with the System.String function. Vb.net 1054 09/09/2023 Vb.net String Array Manipulation count split explode [Return number of element in array] dotg.count= items in array [Split a patterned string into separate elements like a csv file] myfile="dog,10,cat,40,fish,50" dotg=split(myfile,",") Vb.net 1039 09/09/2023 Vb.net String Some Good String Functions concat length mid [CHAR] '// see indexof also Dim myString As String = "ABCDE" Dim myChar As Char myChar = myString.Chars(3) '//myChar = "D" [CONCAT] Dim aString As String = "A" Dim bString As String = "B" Dim cString As String = "C" Dim dString As String = "D" Dim myString As String ' myString = "ABCD" myString = String.Concat(aString, bString, cString, dString) [INDEXOF] '// see char also Dim myString As String = "ABCDE" Dim myInteger As Integer myInteger = myString.IndexOf("D") ' myInteger = 3 [instr] [left] [LENGTH] Dim MyString As String = "This is my string" Dim stringLength As Integer ' Explicitly set the string to Nothing. MyString = Nothing ' stringLength = 0 stringLength = Len(MyString) ' This line, however, causes an exception to be thrown. stringLength = MyString.Length [MID] '//see substring. first charcter is position 1 Dim aString As String = "SomeString" Dim bString As String bString = Mid(aString, 3, 3) [right] [SPLIT] '// returns an array Dim shoppingList As String = "Milk,Eggs,Bread" Dim shoppingItem(2) As String shoppingItem = shoppingList.Split(","c) [SUBSTRING] '//first character is position zero. See mid() Dim aString As String = "A String" Dim bString As String bString = aString.SubString(2,6) '//bString = "String" or Dim aString As String = "Left Center Right" Dim subString As String ' subString = "Center" subString = aString.SubString(5,6) Visual Basic .NET methods are used as inherent functions of the language. They may be used without qualification in your code. The following example shows typical use of a Visual Basic .NET string-manipulation command: In this example, the Mid function performs a direct operation on aString and assigns the value to bString. You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods and instance methods. A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example: Dim aString As String bString = String.Copy("A literal string") In the preceding example, the String.Copy method is a static method, which acts upon an expression it is given and assigns the resulting value to bString. NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing. Comparing Strings You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class. In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used: Dim myString As String = "Alphabetical" Dim secondString As String = "Order" Dim result As Integer result = String.Compare (myString, secondString) This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than a null reference. Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into account, and to compare substrings within the supplied strings. For more information on how to compare strings, see String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method. Searching for Strings Within Your Strings There are times when it is useful to have data about the characters in your string and the positions of those characters within your string. A string can be thought of as an array of characters (Char instances); you can retrieve a particular character by referencing the index of that character through the Chars property. For example: You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following example: Dim myString As String = "ABCDE" Dim myInteger As Integer myInteger = myString.IndexOf("D") ' myInteger = 3 In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can also use the String.LastIndexOf Method to search for the last occurrence of a character in your string. Creating New Strings from Old When using strings, you may want to modify your strings and create new ones. You may want to do something as simple as convert the entire string to uppercase, or trim off trailing spaces; or you may want to do something more complex, such as extracting a substring from your string. The System.String class provides a wide range of options for modifying, manipulating, and making new strings out of your old ones. To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows: You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below: Dim myString As String = "UpPeR oR LoWeR cAsE" Dim newString As String ' newString = "UPPER OR LOWER CASE" newString = UCase(myString) ' newString = "upper or lower case" newString = LCase(myString) ' newString = "UPPER OR LOWER CASE" newString = myString.ToUpper ' newString = "upper or lower case" newString = myString.ToLower The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a given string. For information on these commands, see Format Function or String.Format Method. You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the Visual Basic .NET Trim function. An example is shown: Dim spaceString As String = _ " This string will have the spaces removed " Dim oneString As String Dim twoString As String ' This removes all trailing and leading spaces. oneString = spaceString.Trim ' This also removes all trailing and leading spaces. twoString = Trim(spaceString) If you only want to remove trailing spaces, you can use the String.TrimEnd Method or the RTrim function, and for leading spaces you can use the String.TrimStart Method or the LTrim function. For more details, see LTrim, RTrim, and Trim Functions functions. The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your string. The following example trims all leading and trailing instances of the "#" character: Dim myString As String = "#####Remove those!######" Dim oneString As String OneString = myString.Trim("#") You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method. If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can replace them with another character using the String.Replace Method. For example: Dim aString As String = "This is My Str@o@o@ing" Dim myString As String Dim anotherString As String ' myString = "This is My String" myString = aString.Remove(14, 5) ' anotherString = "This is Another String" anotherString = myString.Replace("My", "Another") You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid Statement can also be used to replace an interior string with another string. You can also use the String.Insert Method to insert a string within another string, as in the following example: Dim aString As String = "This is My Stng" Dim myString As String ' Results in a value of "This is My String". myString = aString.Insert(13, "ri") The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the second parameter is the string to be inserted. You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example: Dim shoppingItem(2) As String Dim shoppingList As String shoppingItem(0) = "Milk" shoppingItem(1) = "Eggs" shoppingItem(2) = "Bread" shoppingList = String.Join(",", shoppingItem) The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the method still adds a separator string between all the empty instances in your array. You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c. The Visual Basic .NET Mid Function can be used to generate substrings of your string. The following example shows this functions in use: Dim aString As String = "Left Center Right" Dim rString, lString, mString As String ' rString = "Right" rString = Mid(aString, 13) ' lString = "Left" lString = Mid(aString, 1, 4) ' mString = "Center" mString = Mid(aString, 6,6) Substrings of your string can also be generated using the String.Substring Method. This method takes two arguments: the character index where the substring is to start, and the length of the substring. The String.Substring method operates much like the Mid function. An example is shown below: There is one very important difference between the String.SubString method and the Mid function. The Mid function takes an argument that indicates the character position for the substring to start, starting with position 1. The String.SubString method takes an index of the character in the string at which the substring is to start, starting with position 0. Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use with the Mid function, but 0,1,2,3,4 for use with the System.String function. Vb.net 1036 09/09/2023 Vb.net Variables Create New Arrays array null Read through entire array For Each fruit As String In MV Console.WriteLine(fruit) Next max number of elements array.length For L = 0 To MV.GetUpperBound(0) elements stored Either Dim strings = New String() {"a", "b", "c"} or Dim strings() As String = {"a", "b", "c"} or strings() As String = {} should work Vb.net 2 09/09/2023