Saving and loading a game in vb.net - vb.net

Is there away I can save or load a game a lot more easier than I have?
Saving Code
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Pugio Cadite\CharacterInformation.txt", True)
file.WriteLine(charactername)
file.WriteLine(characterrace)
file.WriteLine(characterclass)
file.WriteLine(characterGender)
file.WriteLine(charactergold)
file.WriteLine(characterlevel)
file.Close()
and I have not yet wrote the load function.

Imports System.Xml.Serialization
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'save the program variables
Dim p As New ProgramVars
p.Prop1 = "1"
p.Prop2 = "2"
p.Prop3 = "3"
p.Prop4 = "4"
Dim strFilename As String = "C:\Junk\Junk.xml"
p.Save(strFilename)
'load them into a different object
Dim p2 As ProgramVars = ProgramVars.Load(strFilename)
MsgBox(p2.Prop3)
End Sub
End Class
<Serializable>
Public Class ProgramVars
Property Prop1 As String
Property Prop2 As String
Property Prop3 As String
Property Prop4 As String
Sub Save(filename As String)
Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
Dim xs As New XmlSerializer(GetType(ProgramVars))
xs.Serialize(fs, Me)
End Using
End Sub
Shared Function Load(filename As String) As ProgramVars
Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
Dim xs As New XmlSerializer(GetType(ProgramVars))
Return xs.Deserialize(fs)
End Using
End Function
End Class

Related

VB.NET System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Hi any idea why i'm getting this error message?
The original piece of code i'm using which works normally.. However, I decided I wanted to add more values to the code hoping it would work.. but I keep getting this error message. And for project a module was made.
(Module Code)
Module Structure_Units
Structure UnitsStruct
Public ValueOne As String
Public ValueTwo As String
Public ValueThree As String
Public ValueFour As String
Public ValueFive As String
Public ValueSix As String
Public Sub New(rawValue As String)
Dim Values() As String = Split(rawValue, ",")
ValueOne = Values(0)
ValueTwo = Values(1)
ValueThree = Values(2)
ValueFour = Values(3)
ValueFive = Values(4)
ValueSix = Values(5)
End Sub
End Structure
End Module
(Original Code)
Imports System
Imports System.IO
Imports System.Collections
Public Class Structures
Dim Units(3) As UnitsStruct
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Label5.Text = Units(ListBox1.SelectedIndex).ValueOne
Label6.Text = Units(ListBox1.SelectedIndex).ValueThree
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim path As String = "C:\Users\Justi\Desktop\SDD Major Project\NLR.txt"
Dim reader As New System.IO.StreamReader(path)
Dim Index As Integer = -1
While Index < 3
Index += 1
Dim Current As String = reader.ReadLine
Dim fields() As String = Current.Split(";"c)
Units(Index).ValueOne = fields(0)
Units(Index).ValueTwo = fields(1)
Units(Index).ValueThree = fields(2)
ListBox1.Items.Add(Units(Index).ValueTwo)
Label1.Text = Units(Index).ValueOne
Label2.Text = Units(Index).ValueTwo
Label3.Text = Units(Index).ValueThree
End While
End Sub
(New Code I attempted to remake)
Imports System
Imports System.IO
Imports System.Collections
Public Class frmLightRail
Dim Units(7) As UnitsStruct
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Label5.Text = Units(ListBox1.SelectedIndex).ValueOne
Label6.Text = Units(ListBox1.SelectedIndex).ValueThree
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim path As String = "C:\Users\Justi\Desktop\SDD Major Project\NLR.txt"
Dim reader As New System.IO.StreamReader(path)
Dim Index As Integer = -1
While Index < 7
Index += 1
Dim Current As String = reader.ReadLine
Dim fields() As String = Current.Split(";"c)
Units(Index).ValueOne = fields(0)
Units(Index).ValueTwo = fields(1)
Units(Index).ValueThree = fields(2)
Units(Index).ValueFour = fields(3)
Units(Index).ValueFive = fields(4)
Units(Index).ValueSix = fields(5)
ListBox1.Items.Add(Units(Index).ValueTwo)
Label1.Text = Units(Index).ValueOne
Label2.Text = Units(Index).ValueTwo
Label3.Text = Units(Index).ValueThree
Label4.Text = Units(Index).ValueFour
Label5.Text = Units(Index).ValueFive
Label6.Text = Units(Index).ValueSix
End While
End Sub
At first glance, it could go wrong if the code tries to read a line from the NLR.txt input file that contains less than 6 fields (separated by semicolons, not commas).
The code is pretty messy. I have the impression that the "original" code is not complete as well. Was the UnitsStruct part of the original code, or have you added/modified that code as well? Why does the original program only read three lines from the input file and your new code seven lines? Why does the original code split each line into three fields and your new code into six fields?
I guess you should analyze your input file in some more detail and share that information with us by adding it to your question. How many lines does (or can) the input file actually contain? In how many fields should each line actually be split? Does each line have a fixed number of fields, or can the number of fields be different per line?
I made the Structure into a Class and made the fields into Properties. I also added a .ToString method so the ListBox would know what to display.
My test.txt file looks like this.
Mary,had,a,little,lamb,it's
The,quick,brown,fox,jumped,over
Now,is,the,time,for,all
We,the,people,of,the,United
Streams need to be disposed. So, let's simplify by using the System.IO File Class. .ReadAllLines returns an array of lines in the file. We loop through each line, passing it to the constructor of the class which sets all the properties. Then the new UnitClass is added to the list, all fleshed out with its properties.
Create a BindingSource and set its DataSource to the list. The BindingSource becomes the DataSource for the ListBox. The same BindingSource is used for each of the labels. This will syn the ListBox and the Labels. As items in the ListBox are selected the proper values appear in each Label.
Class UnitClass
Public Property ValueOne As String
Public Property ValueTwo As String
Public Property ValueThree As String
Public Property ValueFour As String
Public Property ValueFive As String
Public Property ValueSix As String
Public Sub New(rawValue As String)
Dim Values() As String = Split(rawValue, ",")
ValueOne = Values(0)
ValueTwo = Values(1)
ValueThree = Values(2)
ValueFour = Values(3)
ValueFive = Values(4)
ValueSix = Values(5)
End Sub
'The list box will call .ToString on the UnitClass instance to determin what to display
Public Overrides Function ToString() As String
Return ValueTwo
End Function
End Class
Private UnitBinding As BindingSource
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lst As New List(Of UnitClass)
Dim path As String = "C:\Users\*****\Desktop\test.txt"
Dim lines = File.ReadAllLines(path)
For Each line In lines
Dim unit As New UnitClass(line)
lst.Add(unit)
Next
UnitBinding = New BindingSource
UnitBinding.DataSource = lst
ListBox1.DataSource = UnitBinding
Label1.DataBindings.Add(New Binding("Text", UnitBinding, "ValueOne"))
Label2.DataBindings.Add(New Binding("Text", UnitBinding, "ValueTwo"))
Label3.DataBindings.Add(New Binding("Text", UnitBinding, "ValueThree"))
Label4.DataBindings.Add(New Binding("Text", UnitBinding, "ValueFour"))
Label5.DataBindings.Add(New Binding("Text", UnitBinding, "ValueFive"))
Label6.DataBindings.Add(New Binding("Text", UnitBinding, "ValueSix"))
End Sub

Utilizing wildcards and variables for getFiles

I am kinda new to VB.net, so I am not sure if I try this the right way. I have the following piece of code.
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim TextLine As String
Do While objReader.Peek() <> -1
Dim newString As String = TextLine.Replace(vbCr, "").Replace(vbLf, "") & ".wav"
Dim SongName As String = My.Computer.FileSystem.GetName(newString)
Dim MyFile As String = Dir("C:\AllSongs\" & newString)
Dim Searchquery As IEnumerable(Of String) = IO.Directory.EnumerateFiles("C:\AllSongs", "*", IO.SearchOption.AllDirectories).Where(Function(f) IO.Path.GetFileNameWithoutExtension(f).IndexOf(SongName, StringComparison.CurrentCultureIgnoreCase) >= 0)
For Each Result In Searchquery
ListBox1.Items.Add(Result)
Next
I am trying to use the lines in the text file, and get the .wav in AllSongs dir that partially correspond in these files. Can it be done?
Edit: Part of the code contains a media player. I want to be able to play songs from this player, by choosing files in the list.
Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
AxWindowsMediaPlayer1.URL = ListBox1.SelectedItem
Dim variables As New Dictionary(Of String, String)()
Dim selectedItem As Object = ListBox1.SelectedItem
variables("MyDynamicVariable") = selectedItem ' Set the value of the "variable"
selectedItem1 = selectedItem
Dim value As String = variables("MyDynamicVariable") ' Retrieve the value of the variable
End Sub
Incidental to the question, but important, is that when you're working with files it's often necessary to clean up some resources (file handles, I guess) that the operating system uses even though you don't see it directly in the code as written. There is a way of doing that automatically with the Using statement, as shown in the following code.
To find out if a filename contains some text (string), you can extract the filename with no path or extension with Path.GetFileNameWithoutExtension and check if it contains the desired string with the IndexOf function, which lets you ignore uppercase/lowercase by specifying how to do the check.
I notice from an update to the question that some improvements can be made, such as using a Class for the song entries so that the displayed list can have more information behind it, which means that the song name can be shown on its own but you can get the full path to the file when you click on it.
I made a new Windows Forms project and added just a ListBox to it, and used this code to show the full path (which you can use for your media player) to the song when its name is double-clicked:
Imports System.IO
Public Class Form1
Public Class SongEntry
Property Name As String
Property FullName As String
End Class
Sub PopulateSongList(musicDirectory As String, songsList As String)
Dim songList As New List(Of SongEntry)
Using sr As New System.IO.StreamReader(songsList)
Do While Not sr.EndOfStream
Dim thisSong = sr.ReadLine()
If thisSong <> "NaN" Then
Dim fs = Directory.EnumerateFiles(musicDirectory, "*.wav", SearchOption.AllDirectories).
Where(Function(f) Path.GetFileNameWithoutExtension(f).IndexOf(thisSong, StringComparison.CurrentCultureIgnoreCase) >= 0).
Select(Function(g) New SongEntry With {.Name = Path.GetFileNameWithoutExtension(g), .FullName = g})
songList.AddRange(fs)
End If
Loop
End Using
ListBox1.DataSource = songList
ListBox1.DisplayMember = "Name"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
Dim lb = DirectCast(sender, ListBox)
If lb.SelectedIndex >= 0 Then
Dim fullPathToSong = lb.SelectedValue.ToString()
MsgBox(fullPathToSong)
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim songsList = "C:\temp\AllSongs\songsList.txt"
Dim musicDirectory = "C:\temp\AllSongs"
PopulateSongList(musicDirectory, songsList)
End Sub
End Class

store setting in relative path to executable aplication

I am developing an application to run from USB, is it like a dock/launcher application but I have a problem.
I want to use My.Settings class to save my app settings, but it saves the setting file in AppData folder e.g. C:\Users\<user_name>\AppData\Local\...\...\user.config
I don't want that. I want to save in a path and name of my defined, e.g. My.Application.Info.DirectoryPath & "\Settings.xml"
How can I achieve this?
Update Example of final XML:
<?xml version="1.0" encoding="utf-8"?>
<conf>
<pos>1</pos>
<btn index="1" value="D:\League of Legends\" perm="true">LeagueClient.exe</btn>
<btn index="2" value="D:\RuneLite\" perm="false">RuneLite.exe</btn>
<btn index="3" value="" perm="false"></btn>
<btn index="4" value="" perm="false"></btn>
</conf>
Full project in Github coming soon!!!
Work way for me :
Imports System.IO
Imports System.Xml
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ValConfFile()
End Sub
Public Sub ValConfFile()
If File.Exists("config.xml") = False Then : CreateConfXML() : End If
End Sub
Public Sub CreateConfXML()
Dim obj As Object
Dim archivo As Object
Dim x As Integer = 1
obj = CreateObject("Scripting.FileSystemObject")
archivo = obj.CreateTextFile("config.xml", True)
archivo.WriteLine("<?xml version='1.0' encoding='utf-8'?>")
archivo.WriteLine("<conf>")
archivo.WriteLine("<pos>1</pos>")
For x = 1 To 4
archivo.WriteLine("<btn index='" & CStr(x) & "' value='' perm='false'></btn>")
Next
archivo.WriteLine("</conf>")
archivo.Close()
End Sub
End Class
XML Serialization can be used for this, and is actually fairly straightforward. All you need to do is design one or more classes for your data, then apply the appropriate attributes (their name are in the form Xml...Attribute) in order to serialize them the way you want.
In this setup I've used four different attributes:
XmlElement - Usually the most common one. Specifies that a property will be serialized as an element of its own. The resulting name can be customized by setting the ElementName parameter in the constructor.
If used on lists or arrays, it applies to each item in the collection.
XmlRoot - Pretty much the same as XmlElement, but used for the root element (the class itself).
XmlAttribute - Specifies that a property will be serialized as an attribute (name="value") applied to the parent object, instead of as an element inside it.
XmlText - Specifies that a property's value will be serialized as the contents between the tags of the parent object (i.e. <object>property value</object>).
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
<XmlRoot(ElementName:="conf")>
Public Class Config
<XmlElement(ElementName:="pos")>
Public Property Position As Integer
<XmlElement(ElementName:="btn")>
Public Property Buttons As New List(Of ConfigButton)
Public Sub New()
End Sub
Public Sub New(ByVal Position As Integer)
Me.Position = Position
End Sub
Public Shared Function Load(ByVal File As String) As Config
Using FStream As New FileStream(File, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim Serializer As New XmlSerializer(GetType(Config))
Return Serializer.Deserialize(FStream)
End Using
End Function
Public Sub Save(ByVal File As String)
Using FStream As New FileStream(File, FileMode.Create, FileAccess.Write, FileShare.None)
Dim Serializer As New XmlSerializer(GetType(Config))
Serializer.Serialize(FStream)
End Using
End Sub
End Class
Public Class ConfigButton
<XmlText()>
Public Property DisplayName As String
<XmlAttribute("index")>
Public Property Index As Integer
<XmlAttribute("perm")>
Public Property Perm As Boolean
<XmlAttribute("value")>
Public Property Value As String
Public Sub New()
End Sub
Public Sub New(ByVal DisplayName As String, ByVal Value As String, ByVal Index As Integer, ByVal Perm As Boolean)
Me.DisplayName = DisplayName
Me.Value = Value
Me.Index = Index
Me.Perm = Perm
End Sub
End Class
Usage example:
Private cfg As Config
'
'Loading the config.
'
Private Sub Form1_Load(sender As Object, e As EventArgs) Handled MyBase.Load
If File.Exists("config.xml") Then
cfg = Config.Load("config.xml")
Else
cfg = New Config()
End If
End Sub
'
'Saving the config.
'
Private Sub Form1_FormClosed(sender As Object, e As EventArgs) Handles Me.FormClosed
cfg.Save("config.xml")
End Sub
Adding a button:
cfg.Buttons.Add(New ConfigButton("RuneLite.exe", "D:\RuneLite\", 2, False))
Iterating buttons:
For Each btn As ConfigButton In cfg.Buttons
MessageBox.Show(btn.DisplayName)
Next
Removing a button at a specific index:
'Removes the fourth button.
cfg.Buttons.RemoveAt(3)

Insert string to <input> tag

I'm developing a client that connects to my server, and get access to download and upload files, and i seem to be stuck at uploading files. Here is my code on my VB.NET client:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Upload button
WebBrowser1.Visible = True
'Style OpenFileDialog1
OpenFileDialog1.Title = "Select file to upload"
OpenFileDialog1.InitialDirectory = System.Environment.SpecialFolder.Desktop
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
uploadFile = OpenFileDialog1.FileName.ToString()
If uploadFile = Nothing Then
MessageBox.Show("You just selected nothing.", "Information")
Else
WebBrowser1.Document.GetElementById("fileselect").SetAttribute("value", uploadFile)
WebBrowser1.Document.GetElementById("submit").InvokeMember("click")
End If
End Sub
And here is the HTML code:
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<button type="submit" id="submit" class="uploadButton">Upload Files</button>
Also how do i make so that i can select multiple files? Via the web version you can select multiple files and it workes not not here?
So, as mentioned in the comments, input elements of type file do not allow for external modification, all interaction with them is done through the browser and is based on direct user interaction.
However, you could create an upload class that process the multiple file upload to your server, by creating a HttpWebRequest, which sends the data to the form. Provided there is no authentication, it can be done in the following way.
An interface that allows for some elementary actions for post data items
Public Interface IPostItem
ReadOnly Property Title As String
Property ElementName As String
Function GetPostData(inputNameElement As String) As String
End Interface
Some way to define the mime type of the file being sent
Public NotInheritable Class MimeTypeHandler
Private Shared ReadOnly images As String() = {"jpg", "gif", "bmp", "png", "jpeg"}
Public Shared Function GetMimeType(filename As String) As String
Dim extension As String = Path.GetExtension(filename).Replace(".", "")
If (images.Contains(extension)) Then
Return "image/" + extension
End If
Return "application/" + extension
End Function
End Class
Implement the IPostItem with an implementation that can post the file
Public Class FileQueueItem
Implements IPostItem
Public Property FileName As String
Public Property ElementName As String Implements IPostItem.ElementName
Public Function GetData() As Byte()
Dim result As Byte() = Nothing
Dim lengthRead As Integer = 0
Using stream As New FileStream(FileName, FileMode.Open, FileAccess.Read)
ReDim result(stream.Length)
lengthRead = stream.Read(result, 0, stream.Length)
End Using
Return result
End Function
Public ReadOnly Property ShortName As String Implements IPostItem.Title
Get
Return FileName.Substring(FileName.LastIndexOf("\") + 1)
End Get
End Property
Public ReadOnly Property MimeType As String
Get
Return MimeTypeHandler.GetMimeType(FileName)
End Get
End Property
Public Function GetPostData(inputNameElement As String) As String Implements IPostItem.GetPostData
Dim message As String = String.Empty
message += String.Format("Content-Disposition: form-data; name=""{0}""; filename=""{1}""{3}Content-Type: {2}{3}Content-Transfer-Encoding: base64{3}{3}", inputNameElement, ShortName, MimeType, Environment.NewLine)
message += Convert.ToBase64String(GetData())
Return message
End Function
Public Sub New(filename As String, elementName As String)
Me.FileName = filename
Me.ElementName = elementName
End Sub
End Class
Have a small controller class that runs the upload sequence using the BackgroundWorker class, it sends the files per 5 (can be set, is default value).
It requires a FormUrl, to say where the form is that is being posted to, in my case, i was running it on my localhost, so that you would see in the form code
Public Class FileUploader
Inherits BackgroundWorker
Private ReadOnly _listQueue As IList(Of IPostItem) = New List(Of IPostItem)
Public Property FormUrl As String
Public ReadOnly Property ListQueue As IList(Of IPostItem)
Get
Return _listQueue
End Get
End Property
Public Property MaxPerQueue As Integer
Protected Function HandleResponse(request As HttpWebRequest) As Boolean
Dim success As Boolean = False
Try
Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
success = response.StatusCode <> HttpStatusCode.OK
End Using
Catch ex As WebException
If ex.Response IsNot Nothing Then
ex.Response.Close()
End If
End Try
Return success
End Function
Protected Sub Run(sender As Object, e As DoWorkEventArgs)
If ListQueue.Count = 0 Then
' nothing to upload
Return
End If
' create the boundary string, used to split between the separate attachments
Dim boundary As String = String.Format("--------------------------{0}", DateTime.Now.Ticks)
Dim count As Integer = 0
Dim totalFiles As Integer = ListQueue.Count
Do
' create the request
Dim request As HttpWebRequest = CType(WebRequest.Create(Me.FormUrl), HttpWebRequest)
Dim fullPostMessage As String = String.Empty
request.AllowAutoRedirect = True
request.KeepAlive = True
request.Referer = Me.FormUrl
''// say that it has to post data
request.Method = WebRequestMethods.Http.Post
''// same style like a form
request.ContentType = "multipart/form-data;boundary=" + boundary
count = 0
Dim queueItem As IPostItem
While count < MaxPerQueue AndAlso ListQueue.Count > 0
''// get the item in the queue
queueItem = ListQueue(0)
''// report potential changes to gui
Report(queueItem.Title, count, totalFiles)
Dim postAsString As String = queueItem.GetPostData(queueItem.ElementName)
fullPostMessage &= String.Format("--{0}{1}{2}{1}", boundary, Environment.NewLine, postAsString)
''// remove the item from the queue
ListQueue.RemoveAt(0)
count += 1
End While
fullPostMessage &= "--" & boundary & "--"
Dim postData As Byte() = System.Text.Encoding.ASCII.GetBytes(fullPostMessage)
''// write data to the requestStream (post data)
request.ContentLength = postData.Length
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(postData, 0, postData.Length)
requestStream.Close()
''// handle the response
HandleResponse(request)
requestStream.Dispose()
Loop While ListQueue.Count > 0
ListQueue.Clear()
Report("(Idle)", 0, 100)
End Sub
Protected Sub Report(filename As String, fileIndex As Integer, maxFiles As Integer)
Dim percentage As Integer = (fileIndex * 100) / maxFiles
ReportProgress(percentage, filename)
End Sub
Public Sub New()
Me.WorkerReportsProgress = True
AddHandler Me.DoWork, AddressOf Run
MaxPerQueue = 5
End Sub
End Class
Then you could create your form like this:
And then add the FileUploader class as a private member, so you can get notified when it has completed the upload stream, add the eventhandlers to get notified on the changes
Imports System.ComponentModel
Imports System.Net
Imports System.IO
Public Class Form1
Private fileUploadHandler As New FileUploader()
Private Sub btnUploadFiles_Click(sender As Object, e As EventArgs) Handles btnUploadFiles.Click
fileUploadHandler.FormUrl = "http://localhost:5555/Default.aspx"
Using openDialog As New OpenFileDialog
openDialog.Multiselect = True
openDialog.Title = "Select files to upload to the server"
If openDialog.ShowDialog() Then
' all files are selected
For Each fileName As String In openDialog.FileNames
Dim qItem As IPostItem = New FileQueueItem(fileName, "fileInfo[]")
fileUploadHandler.ListQueue.Add(qItem)
Next
btnUploadFiles.Enabled = False
fileUploadHandler.RunWorkerAsync()
End If
End Using
End Sub
Private Sub OnUploadCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
btnUploadFiles.Enabled = True
End Sub
Private Sub OnReportProgress(sender As Object, e As ProgressChangedEventArgs)
pbUploadProgress.Value = e.ProgressPercentage
lblUploadProgress.Text = e.UserState
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler fileUploadHandler.RunWorkerCompleted, AddressOf OnUploadCompleted
AddHandler fileUploadHandler.ProgressChanged, AddressOf OnReportProgress
End Sub
End Class
The files get then uploaded as soon as you click the Open button in the OpenFileDialog.
As to your second question, to allow for more than 1 file selected, you have to set the OpenFileDialog.Multiselect = True flag

Sharing a List of(String) between Private Sub

In my code I basically read a textbox and put each line into a list (Of String) Dim "testblock" in code below
From there I create another list (of string) and split each line whenever a space is found. Dim "block" in code below
Now I want to be able to access that list from anywhere in the project.
How do I go about sharing a List of(String) between Private Sub such as form buttons?
Private Sub PhaseCodeBTN_Click(sender As Object, e As EventArgs) Handles PhaseCodeBTN.Click
Dim testblock As New List(Of String)
Dim lines As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim block As New List(Of String)
For Each l As String In lines
testblock.Add(l)
Dim words As String() = BlockCodeBox.Text.Split(" ")
For Each splitword As String In words
block.Add(splitword)
Next
Next
BlockCodeBox.Text = testblock(BlockNumBox.Text)
WordCmdBox.Text = block(WordNumBox.Text)
End Sub
Private Sub PhaseBlackBTN_Click(sender As Object, e As EventArgs) Handles PhaseBlackBTN.Click
WordCmdBox.Text = block(WordNumBox.Text)
End Sub
Create a Public Shared Class with your List(Of String) there to use it anywhere in the project:
Public Shared Class DataHolder
Private _block As New List(Of String)
Public Property Block As List(Of String)
Get
Return _block
End Get
Set
_block = value
End Set
End Property
End Class
Example:
Either simply use DataHolder.Block.Add(splitword) OR following steps:
Declare a class variable block to use it in entire class:
Private block As List(Of String)
Initialize it in some suitable function / event-handler like Form_Load:
block = DataHolder.Block
Do the operation:
block.Add(splitword)