Is there a way to extract a variable from a subroutine in vb .net? or how do I declare custom event handlers and trigger them in a linked fashion? - vb.net

I am trying to build this file copy utility in VB.Net, and I have this window:
The current folder button opens up a folder browser dialog, and I save the selected path from the dialog to a string variable which I then pass to a function. The function adds all files and directories present in that folder to the current folder listbox.
Now I need this filepath for the all files checkbox, which when triggered lists all the subdirectories and their contents in the currentfolder listbox.
Is there any way I can extract that filepath variable dynamically without hardcoding it? Or can I create custom event handlers and trigger them inside the current folder button handler?
Here is my code:
Public Class Form1
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FB As FolderBrowserDialog = New FolderBrowserDialog()
Dim srcpath As String
Dim flag As Integer = 1
FB.ShowDialog()
FB.ShowNewFolderButton = True
If (DialogResult.OK) Then
srcpath = FB.SelectedPath()
End If
listfiles(srcpath)
End Sub
Public Function listfiles(srcpath As String)
Dim dir As DirectoryInfo = New DirectoryInfo(srcpath)
Dim dirs As DirectoryInfo() = dir.GetDirectories()
Dim d As DirectoryInfo
Dim files As FileInfo() = dir.GetFiles()
Dim file As FileInfo
For Each file In files
CurrentFolderListBox.Items.Add(file.Name)
Next
For Each d In dirs
CurrentFolderListBox.Items.Add(d)
Next
'If CheckBox1.Checked = True Then
' CheckBox1_CheckedChanged(sender, New System.EventArgs())
'End If
End Function
Public Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChange
Dim item As DirectoryInfo
For Each i As DirectoryInfo In CurrentFolderListBox.Items
item = i
Next
End Sub
Any help would be most appreciated.

Well, for the list side lbox, and the right side lbox?
Why not fill each list box with a data source? You can have 1, or 2, or even 5 columns of data. The ListBox can display TWO of the columns.
So, VERY often a list box will have two values. the "value" based on what you select (often a PK database row value), and then you have the "text" value for display.
from FoxPro, ms-access, vb.net, and even asp.net?
A list box traditional has had the ability to "store" a set of values for your selection.
So, why not just put out the file list to a on the fly "data structure". You can quite much use a struct, a class or whatever.
However, might as well use a data table, since listbox supports "binding" to a table.
So, in the ListBox settings, you have these two settings:
so above is our "display"
And then set the "value" to the FULL file name like this:
So now we can say create a form like this:
So, our code to select the "from folder" can look like this:
Private Sub cmdSelFrom_Click(sender As Object, e As EventArgs) Handles cmdSelFrom.Click
Dim f As New FolderBrowserDialog
If f.ShowDialog = DialogResult.OK Then
txtFromFolder.Text = f.SelectedPath
ListBox1.DataSource = GetFileData(txtFromFolder.Text)
End If
End Sub
Public Function GetFileData(sFolder As String) As DataTable
Dim rstData As New DataTable
rstData.Columns.Add("FullFile", GetType(String))
rstData.Columns.Add("FileName", GetType(String))
' get all files from this folder
Dim folder As New DirectoryInfo(sFolder)
Dim fList() As FileInfo = folder.GetFiles
For Each MyFile As FileInfo In fList
Dim OneRow As DataRow = rstData.NewRow
OneRow("FullFile") = MyFile.FullName
OneRow("FileName") = MyFile.Name
rstData.Rows.Add(OneRow)
Next
Return rstData
End Function
so, we setup a two column "thing" (in this case a data table).
We fill it with our two values (FileName and FullFile).
So, we now have this:
I have selected two files on the left side, and thus we get this:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
For Each MySel As DataRowView In ListBox1.SelectedItems
Debug.Print(MySel.Item("FileName"))
Debug.Print(MySel.Item("FullFile"))
Next
End Sub
OutPut:
a.pdf
C:\Test2\a.pdf
b.pdf
C:\Test2\b.pdf
We could even include say file size in that table. But the "basic" concept here is that we can store + save data items into the list box, and that REALLY makes the code simple, since the list box now has JUST the file for display, but also enables us to have the full path name also.

Related

Multiple Selections from Listbox to rename Folders

Have a vb.net userform with a listbox set to multiselect. This is for personal use. The listbox populates itself when the form loads with all the subfolders, by name only, in a designated folder. I want to append a prefix to each selected folder in the listbox.
By default, all folders would have the prefix, let's say X. So, for example, Xfolder1 becomes folder1 if selected and the submit button is pressed (not on listbox change).
Here is my code and pseudocode so far. Getting string errors. Only the first sub, loading the form and populating the list works. Many thanks for any help. Health and safety to all during this pandemic.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each folder As String In System.IO.Directory.GetDirectories("D:\TestFolder\")
ListBox1.Items.Add(Path.GetFileName(folder))
Next
End Sub
This is ofc pseudocode
Private Sub RenameFolders(sender As Object, e As EventArgs) Handles Button1.Click
For i = 0 To ListBox1.Items.Count - 1
If Prefix Exists Then
FileIO.FileSystem.RenameDirectory(Prefix & FolderName, FolderName)
Else
FileIO.FileSystem.RenameDirectory(FolderName, Prefix & FolderName)
End If
Next
End Sub
What is above and lots of research. Issue might be with whether my strings are the full path or just the folder name. Listbox returns folder names, but is that what the code returns? Very confused.
Hi. Sorry for the lack of clarity. Because the listbox is populated on load, it will show the current state of the folders. This could be Xfolder1, folder2, xfolder3 etc. It will be the folder names as they currently exist.
Another way to look at it.
Selecting folders will remove any prefix from all selected when submit is hit.
Not selecting folders will add the prefix to all non-selected when submit is hit.
If xfolder1 appears in the listbox and is selected, it becomes folder1.
If xfolder1 appears in the listbox and is NOT selected, it remains xfolder1.
If folder1 appears in the listbox and it is selected, it remains folder1.
If folder1 appears in the listbox but is NOT selected, it changes to xfolder1
I hope that makes more sense?
Assuming that I'm understanding your question properly now, I would suggest that you use the DirectoryInfo class. You can create one for the parent folder and then get an array for the subfolders. You can then bind that array to the ListBox and display the Name property, which is just the folder name, while still having access to the FullName property, which is the full path. It also has an Exists property and a MoveTo method for renaming. Here is how I would do what you're asking for:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folderPath = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Test")
Dim folder As New DirectoryInfo(folderPath)
Dim subFolders = folder.GetDirectories()
With ListBox1
.DisplayMember = "Name"
.DataSource = subFolders
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Const prefix As String = "X"
For Each selectedSubFolder As DirectoryInfo In ListBox1.SelectedItems
'This is required to update the Exists property if the folder has been deleted since loading.
selectedSubFolder.Refresh()
If selectedSubFolder.Exists Then
Dim parentFolderPath = selectedSubFolder.Parent.FullName
Dim folderName = selectedSubFolder.Name
If folderName.StartsWith(prefix) Then
folderName = folderName.Substring(prefix.Length)
Else
folderName = prefix & folderName
End If
Dim folderPath = Path.Combine(parentFolderPath, folderName)
selectedSubFolder.MoveTo(folderPath)
End If
Next
End Sub
End Class
Note that this doesn't update the ListBox as it is. If you want that too, here's how I would do it with the addition of a BindingSource:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folderPath = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Test")
Dim folder As New DirectoryInfo(folderPath)
Dim subFolders = folder.GetDirectories()
BindingSource1.DataSource = subFolders
With ListBox1
.DisplayMember = "Name"
.DataSource = BindingSource1
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Const prefix As String = "X"
For Each selectedSubFolder As DirectoryInfo In ListBox1.SelectedItems
'This is required to update the Exists property if the folder has been deleted since loading.
selectedSubFolder.Refresh()
If selectedSubFolder.Exists Then
Dim parentFolderPath = selectedSubFolder.Parent.FullName
Dim folderName = selectedSubFolder.Name
If folderName.StartsWith(prefix) Then
folderName = folderName.Substring(prefix.Length)
Else
folderName = prefix & folderName
End If
Dim folderPath = Path.Combine(parentFolderPath, folderName)
selectedSubFolder.MoveTo(folderPath)
End If
Next
BindingSource1.ResetBindings(False)
End Sub
End Class
Note that this will still not resort the data but I'll leave that to you if you want it. The reason is that you could do a simple sort of the DirectoryInfo array on Name but that will do a straight alphabetic sort, which the ListBox can already do. If you want a logical sort like File Explorer does, where actual numbers in folder names are sorted numerically, then you need to use a Windows APi function too, which is beyond the scope of this question. If you want that, see here for more information.

VB.NET Program is always reading last created textfile

Trying to create a login form,
My coding is currently:
Imports System
Imports System.IO
Public Class frmLogin
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String
Dim files As Integer
Dim filepath As String
Public Structure info
Dim U As String
Dim P As String
End Structure
Dim details As info
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If txtusername.Text = details.U And txtpassword.Text = details.P Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
End Sub
Private Sub btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
files = files + 1
filepath = "C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt"
Dim di As DirectoryInfo = New DirectoryInfo("C:\Users\TheGlove\Desktop\Alex's Program")
folderpath = "C:\Users\TheGlove\Desktop\Alex's Program"
files = System.IO.Directory.GetFiles(folderpath, "*.txt").Count
For Each fi In di.GetFiles()
MsgBox(fi.Name)
Dim FILE = System.IO.File.ReadAllLines("C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt")
Dim myArray As String() = FILE
details.U = myArray(0)
details.P = myArray(1)
Next
End Sub
End Class
Button 1 will be merged with btnlogin when i get it working and for now is currently just a seperate button to read each textfile.
When each button is pressed (Button 1 -> btnlogin), only the last created textfile is correct.
By the looks of things, your code does read all the text files, but keeps overwriting details.u and details.p with the value retrieved from each file. So, when the loop gets to the last file, those values are what ends up in the details object.
I'm assuming that you want to read all the usernames and passwords into a list and check the details in the TextBoxes against that list, so .. Your code should probably be something like the code below (see the code comments for an explanation of some of the differences.
Before we get to the code, can give you a couple of pointers.
Firstly, always try to use names that are meaningful. Defining your structure as Info is not as meaningful as it could be. For example, you would be better calling it UserInfo and rather than use P and U, you would be better using Password and UserName. It may not matter so much right now, but when you start writing larger more complex programs, and have to come back to them in 6 months time to update them, info.P or details.P aren't as informative as the suggested names.
Secondly, as #ajd mentioned. Don't use magic strings. Create one definition at the beginning of your code which can be used throughout. Again it makes maintenance much easier if you only have to change a string once instead of multiple times, and reduces the chance of mistakes.
Finally, several of the variables you have defined aren't used in your code at all. Again, at this level, it isn't a major issue, but with large programs, you could end up with a bigger memory footprint than you want.
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String = "C:\Users\TheGlove\Desktop\Alex's Program"
Dim files As Integer
Dim filepath As String
Public Structure UserInfo
Dim Name As String
Dim Password As String
End Structure
'Change details to a list of info instead of a single instance
Dim userList As New List(Of UserInfo)
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
'Iterate through the list of details, checking each instance against the textboxes
For Each tempUserInfo As UserInfo In userList
If txtusername.Text = tempUserInfo.Name And txtpassword.Text = tempUserInfo.Password Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
'This is here, because after your form has opened an closed, the loop
'that checks usernames and passwords will continue. The line below exits the loop safely
Exit For
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
Next
End Sub
Private Sub Btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'clear the list of user details otherwise, if the files are loaded a second time,
'you'll get the same details added again
userList.Clear()
'This line replaces several lines in your code that searches the folder for files
'marching the search pattern
Dim fileList() As FileInfo = New DirectoryInfo(folderpath).GetFiles("loginfile*.txt")
For Each fi As FileInfo In fileList
MsgBox(fi.Name)
Dim userDetails() As String = System.IO.File.ReadAllLines(fi.FullName)
Dim tempInfo As New UserInfo With {.Name = userDetails(0), .Password = userDetails(1)}
'An expanded version of the above line is
'Dim tempInfo As New info
'tempInfo.U = userDetails(0)
'tempInfo.P = userDetails(1)
userList.Add(tempInfo)
Next
files = fileList.Count
End Sub

.NET Delete actual files from listbox

This code is intended to delete the actual files from the system when it is selected from the system:
Dim file As String()
file = System.IO.Directory.GetFiles("C:\Users\User\Desktop", "lalala.txt", IO.SearchOption.AllDirectories)
If ListBox1.SelectedIndex = -1 Then
MsgBox("No files selected")
Else
System.IO.File.Delete(ListBox1.Items(ListBox1.SelectedIndex).ToString())
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
End If
However, only the items in the listbox are deleted. The actual file still exists. I am unsure where I should put the file into the Delete function.
I have referred to this but it has not helped me.
________UPDATE________
I have discovered where it went wrong: it is because only the file name is added to the listbox:
ListBox1.Items.Add(Path.GetFileName(fileFound))
Instead of Path.GetFullPath.
Anyhow, can I delete the file with GetFileName only?
The problem, as you realised, is that the filename only is not enough information to delete a file. You need the whole path to the file as well. So you need some way of storing the whole path but only showing the filename. This is also important because there might be two (or more) files with same name in separate directories.
A ListBox can have its Datasource property set to show items from "an object that implements the IList or IListSource interfaces, such as a DataSet or an Array."
Then you set the DisplayMember and ValueMember properties to tell it what to display and what to give as the value.
For example, I made up a class named "FileItem" which has properties for the full filename and for whatever you want to display it as, filled a list with instances of "FileItem", and told ListBox1 to display it:
Imports System.IO
Public Class Form1
Class FileItem
Property FullName As String
Property DisplayedName As String
Public Sub New(filename As String)
Me.FullName = filename
Me.DisplayedName = Path.GetFileNameWithoutExtension(filename)
End Sub
End Class
Private Sub PopulateDeletionList(dir As String, filter As String)
Dim files = Directory.EnumerateFiles(dir, filter, SearchOption.AllDirectories)
Dim fileNames = files.Select(Function(s) New FileItem(s)).ToList()
Dim bs As New BindingSource With {.DataSource = fileNames}
ListBox1.DataSource = bs
ListBox1.DisplayMember = "DisplayedName"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
Dim lb = DirectCast(sender, ListBox)
Dim sel = lb.SelectedIndex
If sel >= 0 Then
Dim fileToDelete = CStr(lb.SelectedValue)
Dim choice = MessageBox.Show("Do you really want to delete " & fileToDelete, "Confirm file delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If choice = DialogResult.Yes Then
Try
File.Delete(fileToDelete)
lb.DataSource.RemoveAt(sel)
Catch ex As Exception
MessageBox.Show("Could not delete " & fileToDelete & " because " & ex.Message)
End Try
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateDeletionList("C:\temp", "*.txt")
End Sub
End Class
Edited I had forgotten to delete the item from the ListBox. To do that, it needs to be tied to the DataSource through a BindingSource.
Extra feature Seeing as there could be more than one file with the same name, you might want to add a tooltip to the listbox items so that you can see which directory it is in. See how to add tooltips on winform list box items for an implementation which needs only minor adjustments to work, such as:
Dim toolTip As ToolTip = New ToolTip()
' ...
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
Dim lb = DirectCast(sender, ListBox)
Dim index As Integer = lb.IndexFromPoint(e.Location)
If (index >= 0 AndAlso index < ListBox1.Items.Count) Then
Dim desiredTooltip = DirectCast(lb.Items(index), FileItem).FullName
If (toolTip.GetToolTip(lb) <> desiredTooltip) Then
toolTip.SetToolTip(lb, desiredTooltip)
End If
End If
End Sub
The most simple (and reliable) solution would be to create a custom data type and add that to the ListBox instead.
By overriding the ToString() method you can make it display only the file name, while the back-end object still contains the full path.
Public Structure FileEntry
Public FullPath As String 'A variable holding the full path to the file.
'Overriding the ToString() method, making it only return the file name.
Public Overrides Function ToString() As String
Return System.IO.Path.GetFileName(Me.FullPath)
End Function
Public Sub New(ByVal Path As String)
Me.FullPath = Path
End Sub
End Structure
Now whenever you want to add paths to the ListBox you've got to add a new instance of the FileEntry structure, instead of a regular string:
ListBox1.Items.Add(New FileEntry(fileFound))
And to delete you just cast the currently selected item into a FileEntry, and then pass its FullPath onto the File.Delete() method.
Dim Entry As FileEntry = DirectCast(ListBox1.Items(ListBox1.SelectedIndex), FileEntry)
System.IO.File.Delete(Entry.FullPath)
NOTE: For this to work every item in the list box must be a FileEntry.
Online test: https://dotnetfiddle.net/x2FuV3 (pardon the formatting, DotNetFiddle doesn't work very well on a cellphone)
Documentation:
How to: Declare a Structure (Visual Basic) - Microsoft Docs
Overriding the Object.ToString() method - MSDN
You can use Path.Combine.
Since you are going to search in C:\Users\User\Desktop, you can do this to delete:
System.IO.File.Delete(Path.COmbine("C:\Users\User\Desktop",ListBox1.Items(ListBox1.SelectedIndex).ToString())
Here, "C:\Users\User\Desktop" and the selected index's text will be combined to make a single path.
Edit:
I get it, you want to show the file name onlyy in the textbox but want to delete the file from the system too but can't do it, right?
Well you can do this:
Put two listbox and while you add a file to a listbox1, put it's path to the listbox2 whose visibility will be False, meaning it won't be shown in the runtime.
DOing this, while an item is selected in the listbox1, use the path.combine to make a path by adding the filename & path from the list with same index number.
Something like this:
System.IO.File.Delete(path.combine(ListBox1.Items(ListBox1.SelectedIndex).ToString(), ListBox2.Items(ListBox1.SelectedIndex).ToString())

Separate String Lines using StreamReader | VB.net

I am trying to make my own checklist app. I am using a ListView object to display each checklist item. I can add individual items to the object. I don't know how to save the ListView items on exit and then load them in on startup. (I tried using My.Settings, but it doesn't work.)
My solution was to make an import/export system using .txt files to store data. They are formatted like this:
Item1
Item2
Item3
When I import them, it all shows as one long item in ListView. I am using the code below.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim fileReader As String
fileReader =
My.Computer.FileSystem.ReadAllText(ImportFileDialog.FileName)
ImportFileDialog.RestoreDirectory = True
ChecklistObject.Items.Add(fileReader)
End If
End Sub
If anyone knows how to write individual items on their own line in a text file, that would be great too.
EDIT: Exporting doesn't work either. Using code below:
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
ExportFileDialog.Filter = "Keklist Save|*.kek"
If ExportFileDialog.ShowDialog = DialogResult.OK _
Then
ChecklistObject.Items.Item()
End If
End Sub
In your example code you are only adding one item to the list view so it will only show the one line.
You could use System.IO.File.ReadAllLines to read all the lines of the file into a string array.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim path As String = ImportFileDialog.FileName
Dim lines() As String = File.ReadAllLines(path)
ImportFileDialog.RestoreDirectory = True
For Each line in lines
ChecklistObject.Items.Add(line)
Next
End If
End Sub

Using a combo box to store items in an array from a text file and then using that array and its components in another form

I'm currently designing an application within visual basic using vb.net. The first form asks for login information and then prompts the next form to select a customer. The customer information is stored in a text file that gets put in an array. I next have a form for the user to display and edit that information. How can I use the array I already created in the previous form in my display and edit form?
Private Sub frmCustomerList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sr As StreamReader = File.OpenText("customer.txt")
Dim strLine As String
Dim customerInfo() As String
Do While sr.Peek <> -1
strLine = sr.ReadLine
customerInfo = strLine.Split("|")
cboCustomers.Items.Add(customerInfo(0))
customerList(count) = strLine
count = count + 1
Loop
End Sub
Private Sub cboCustomers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCustomers.SelectedIndexChanged
Dim customerInfo() As String
Dim index As Integer = cboCustomers.SelectedIndex
Dim selectedCustomer As String = customerList(index)
customerInfo = selectedCustomer.Split("|")
End Sub
Make the next form require it in the constructor:
Public Class EditCustomer
Public Sub New(customerInfo As String())
InitializeComponent() 'This call is required, do not remove
'Yay! Now you have your info
End Sub
End Class
You'd call it by doing something like...
Dim editForm = New EditCustomerFrom(customerInfo)
editForm.Show()
Alternatively, you could have a property on the form you set.
Dim editForm = New EditCustomerFrom()
editForm.Customer = customerInfo
editForm.Show()
Then inside the Load event of that form, you'd write the logic that would display it looking at that property.
Aside: You should look at maybe defining an object to hold customer info and do some JSON or XML serialization for reading/writing to the file, IMO. This architecture is kind of not good as is....