VB.NET - Adding items to a listview as well as checkboxes and tag property - vb.net

I've got this code which basically loops through a set of folders and subfolders and finds specific file types. And then lists these in a listview. Now, it's intended to list exe and msi files. And I've made it so that these icons can be doubleclicked after they have been listed. I do this by adding the path to the file in it's tag property.
But, my superiors want a checkbox next to each item. So that they can check each item they want installed. And then have a button which runs the path in each tag property one at a time. It's basically the part where I fill the listview with the checkbox, filename of the exe or msi file, tag and the icon that I'm wondering about.
This is the existing code. This includes just a Tile view of the listview.
Public Sub getDirectories(ByVal strFilepath As String, ByVal strFileExtension As String, ByVal objControl As Object)
'Load first files from the root folder. Then loop each subfolder
Dim di As New DirectoryInfo(strFilepath)
Dim aryFi As IO.FileInfo() = di.GetFiles(strFileExtension, SearchOption.AllDirectories)
Dim filePath As String
Dim fileIcon As Icon
' For each file in the root folder
For Each file In aryFi
If file.Extension = String.Empty Then
Else
filePath = GetAssociatedProgram(file.Extension)
On Error Resume Next
'Extract icon
fileIcon = Drawing.Icon.ExtractAssociatedIcon(filePath)
'Add the icon if we haven't got it already
objControl.StateImageList = Form1.iconList
If Form1.iconList.Images.ContainsKey(filePath) Then
Else
Form1.iconList.Images.Add(filePath, fileIcon)
End If
'Add item to list
objControl.items.add(file.Name, filePath).Tag = file.DirectoryName
End If
Next
End Sub
Basically I call this sub in this way:
getDirectories(strProgramLocation, "*.exe", Form1.listViewSupSoftware)
And I've found that I can add items to a listview which also contains columns:
Dim tempstr(2) As String
tempstr(0) = "Name of item"
tempstr(1) = "Target folder of item"
Dim tempNode As ListViewItem
tempNode = New ListViewItem(tempstr)
Form1.listViewItem.Items.Add(tempNode)
But there should be a way of combining these two right? I'm not sure how I can add a checkbox in the first column of the listview? I've already set the Checkbox property of the listview to True. But I could use some pointers here if anyone's got any. :)

Mmm, I don't understand quite well your question. If you already have the listbox you just need to use a CheckedListBox and loop thru all the checked items executing the executable stored into the tag property ...
As I said I'm not sure If I get what you mean ...

Related

How to keep the content of ListBox in Vb.net

If i want to keep the content of a textbox i do this
TextBox1.Text = TextBox1.Text & Something
Is there a way to do the same thing for the content of Items of a Listbox?
In my RichTextBox3 i have the list of files in the C:\Work directory
I Tried this code but it's giving me The content of the last line (It's not adding the lines before)
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop
Help is appreciated
Thanks to all of you
I'm not sure that this will address your stated problem but there's a serious issue with that code and I need to provide a long code snippet to address it and that won't be readable in a comment.
The Lines property of a TextBox or RichTextBox is not "live" data, i.e. it doesn't refer to an array stored within the object. Each time you get the property, a new array is created. You are getting RichTextBox3.Lines twice for every iteration of that loop, so that's obviously wrong. You also should not be adding items to the ListBox one by one like that. You should be creating a list of all the items first, then adding them all with a single call to AddRange:
Dim files As New List(Of FileInfo)
For Each line In RichTextBox3.Lines
Dim folderPath = Path.Combine("C:\Work", line)
Dim folder As New DirectoryInfo(folderPath)
files.AddRange(folder.GetFiles("*", SearchOption.AllDirectories))
Next
ListBox1.Items.AddRange(files.ToArray())
If that code doesn't work as expected, you can debug it and view the contents of files at various stages to make sure that you are getting the files you expect. It might also be worth testing folder.Exists before calling GetFiles, unless you're absolutely sure that each line in the RichTextBox represents an existing folder.
This will do what you want.
number = 0
ListBox1.items.clear()
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop

VB How Do I Get A List of Files in a Specified Directory

I think this is a simple question but I can't get the statement format working. I want to list all the files in a specified directory and sub-directories in a list box. I know this is pretty basic. I searched on the Microsoft doc site and I believe that I want to use the GetFile method below. My problem is that I don't know where I put the directory name.
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments)
listBox1.Items.Add(foundFile)
Next
Dim folderPath As String 'Set folder path here
Dim folder As New DirectoryInfo(folderPath)
Dim files = folder.GetFiles()
With listBox1
.DisplayMember = "Name"
.ValueMember = "FullName"
.DataSource = files
End With
Pretty much always bind as a first option. Adding item by item is generally inferior. The DisplayMember is the property or column to display and the ValueMember is the property or column to expose via the control's SelectedValue. You can set the folderPath to whatever you want, however you want, e.g. let the user choose using a FolderBrowserDialog.
Send all the file names of a directory to a text file :
Imports System.IO
'no need:
'Imports System.Linq
Dim MyFiles As String()
MyFiles = Directory.GetFiles(MyPath).
Select(Function(f) Path.
GetFileNameWithoutExtension(f)).ToArray()
' or WITH extension:
' GetFileName
File.WriteAllLines(MyPath & "Text.txt", MyFiles)

How to display a single Windows Explorer folder (that cannot be navigated away from) within a userform?

I would like to have a box within the userform display the contents of a single folder.
I would like the folder to display icons similar to how Windows Explorer does, and I would also like users to be able to drag icons from other windows into it (just like a real explorer window).
I decided to use a listview, and this will populate it with a bunch of lines of text for each file, but clicking on them does nothing and I cannot drag anything in. Also they don't have icons.
Any ideas?
Dim fileEntries As String() = Directory.GetFiles("C:\Windows\")
For Each fileName As String In fileEntries
ListView1.Items.Add(fileName)
Next
This MSDN article describes exactly how to do this. it even gets the icons, as you requested! It also uses a ListView, too! Enjoy!
As Jeremy said, you will still need to hook up event, if you want it to respond to click (or drag) events.
Private listView1 As ListView
Private imageList1 As ImageList
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo("c:\")
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As System.IO.FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = SystemIcons.WinLogo
item = New ListViewItem(file.Name, 1)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub

How do I set images to listview items when they contain certain text?

Does anyone know how I set images to listview items when they contain certain text? For instance if an items' text is something with ".png" I want to give that item (or those items) an image which I've added to an imagelist.
Here is the code I use to populate the listview with folders and files:
Dim FilePath As String = "C:\"
ControlListView.Items.Clear()
Dim DirInfo() As DirectoryInfo
DirInfo = New DirectoryInfo(FilePath).GetDirectories
For Each DirInfoFolder In DirInfo
ControlListView.Items.Add(DirInfoFolder.Name)
Next
Dim FilePathFiles As New IO.DirectoryInfo(FilePath)
For Each FileInfoFolder In FilePathFiles.GetFiles
ControlListView.Items.Add(FileInfoFolder.Name)
Next
Any help would be appriciated. Thanks in advance :)
Instead of using the default ListView.Add(string), you need to construct your own ListViewItem and then add it to the ListView after setting the correct index for the image in the image list. (My VB.Net is rusty so please verify the syntax)
For Each FileInfoFolder In FilePathFiles.GetFiles
Dim lvi as New ListViewItem(FileInfoFolder.Name)
If FileInfoFolder.Name.EndsWith(".png")
lvi.ImageIndex = pngImageIndex
End If
ControlListView.Items.Add(lvi)
Next

How to make textfile to save in program directory in Visual Studio

As i have abandoned the array approach to the problem, i need to know how to make listbox to save in textfile always in program's directory so it can be used/accessed to populate a different listbox, any ideas? Below is my code.
SaveFileDialog1.Filter = "Text files (.txt)|.txt"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName <> "" Then
Using SW As New IO.StreamWriter(SaveFileDialog1.FileName, False)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End If
A little bit of research on your part would've helped you understand what you are trying to accomplish better.
How do I get Program Data directory? My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
How do I Write multiple lines to file? File.WriteAllLines()
How do I Read multiple lines from a file? File.ReadAllLines()
Once you understand the basics you can easily put them together
Create two List boxes, and one button on your WinForm:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.
'Get the Program Data Directory (This is hidden by default by the OS.)
Dim strPath As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Dim fileName As String = "myFile.txt"
Dim fullPath = Path.Combine(strPath, fileName)
Dim data As String() = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
'Save the items to ListBox1 First
For Each item As String In data
ListBox1.Items.Add(item)
Next
'Now write the items to the textfile, line by line.
File.WriteAllLines(fullPath, data)
'Read all lines we just saved and load them onto an array of strings.
Dim tempAllLines() As String = File.ReadAllLines(fullPath)
'Display each on ListBox2 by iterating the array.
For Each line As String In tempAllLines
ListBox2.Items.Add(line)
Next
End Sub
Here, I created this form so you can get an idea of what i'm referring to.
You can get the path to the current executable's folder like this:
folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
However, that will only work if the executable is a .NET assembly. Otherwise, you could use the first argument in the command line (which is the full executable file path), like this:
folderPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()(0))
If, on the other hand, you want to get the path of the current assembly (which may be different than the executable that loaded it) you could do this:
folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Or, if you want to just get the current directory, you could use this:
folderPath = Directory.GetCurrentDirectory()
Once you have the folder path, you can add the file name to it with Path.Combine, like this:
filePath = Path.Combine(folderPath, fileName)
However, it's not recommended that you write data directly to the program's running path, since the user may not have permission to write to that folder. Using the program data folder would certainly be better, but even that can be risky:
folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyAppName")
The recommended place to store data from .NET apps is Isolated Storage.