Storing variables generated by a while loop - arrays

I have a while loop that parses a csv file, and inserts the variables into a series of arrays. This is called by a button on my main form.
These variables are used for a chart (which is in the same sub) and also for a datagrid, which is on a separate form.
The first time I click the button, everything works as normal, however if I click it a second time, the datagrid on the separate form is not populated, as I am losing the variables.
So within the while loop which parses the CSV file, I have this:
frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)
I have tried making the variables public, however because they are arrays, and constructed from the while loop, I can't seem to make them publicly accessible.
My code (edited for brevity)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sFile As String = strFileName
' get the minimum and maximum frequencies
Dim Lines As Collections.Generic.IEnumerable(Of String) = File.ReadLines(strFileName)
Dim Line0 As String = Lines.FirstOrDefault
Dim LineN As String = Lines.LastOrDefault
Dim lowestFreq As String() = Line0.Split(New Char() {","c})
Dim highestFreq As String() = LineN.Split(New Char() {","c})
Dim lowFreq As String = lowestFreq(0)
Dim highFreq As String = highestFreq(0)
Dim refFrequencyX = Lines(18)
Dim refFreq As String() = refFrequencyX.Split(New Char() {","c})
Dim ScaleFactor As String = refFreq(1)
Using sr As New StreamReader(sFile)
While Not sr.EndOfStream
Dim sLine As String = sr.ReadLine()
If Not String.IsNullOrWhiteSpace(sLine) Then
sData = sLine.Split(","c)
arrName.Add(sData(0).Trim())
arrValue.Add(sData(1).Trim())
End If
Dim freq As Decimal = sData(0)
Dim dBu As Decimal = sData(1)
Dim voltage As Decimal = sData(1)
' dbnorm - normalise output to 0dBu ref 1kHz
Dim dbnorm = Math.Round(dBu - ScaleFactor, 4)
frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)
Chart1.Series(0).Points.AddXY(freq, dbnorm)
End While
End Using
' ( chart is constructed here )
end sub
How can I make these array variables global?
Please excuse my shoddy code - I am doing this as a hobby and learning as I go along.

I solved this by adding a public class into a module.
Inside the 'Public Class' I have 'Public Shared Sub' for the subs I want access to from anywhere within the code.
Example:
Public Module Module1
<various public variables here>
Public Class MyData
Public Shared Sub debugTempFile()
' DEBUG
Dim mytempFolder As String = Path.GetTempPath()
Dim MyOutFile As String = mytempFolder + "outfile.txt"
Dim myfile As System.IO.StreamWriter
myfile = My.Computer.FileSystem.OpenTextFileWriter(MyOutFile, True)
myfile.WriteLine(debugdata)
myfile.Close()
' END DEBUG
End Sub
End Class
End Module
This Public Sub can be called from anywhere using the call statement:
Call MyData.debugTempFile()
I hope this is of use to other beginners like myself.

Related

Visual Basic code works but is inelegant - any suggestions?

I am trying to stay ahead of my Year 12 Software class. Starting to work with records and arrays. I have answered the question, but the solution feels very clunky. I am hoping someone has suggestions/links for completing this task in a more efficient way.
The task: read in lines from a text file and into a structure, and then loop through that, populating four list boxes if an animal hasn't been vaccinated.
Here's the code:
Imports System.IO
Public Class Form1
'Set up the variables - customer record, total pets not vaccinated, total records in the file, and a streamreader for the file.
Structure PetsRecord
Dim custName As String
Dim address As String
Dim petType As String
Dim vacced As String
End Structure
Dim totNotVac As Integer
Dim totalRecCount As Integer
Dim PetFile As IO.StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
'set an array of records to store each record as it comes in. Limitation: you need to know how many records in the file. Set the array at 15 to allow for adding more in later.
Dim PetArray(15) As PetsRecord
'variables that let me read in a line and split it into sections.
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
'tell them what text file to read
PetFile = New IO.StreamReader("patients.txt")
totNotVac = 0
Try
totalRecCount = 0
' read each line in and split the lines into fields for the records. Then assign the fields from the array. Finally, reset the array and loop.
Do Until PetFile.Peek = -1
'read in a line of text
lineoftext = PetFile.ReadLine()
'split that line into bits separated by commas. these will go into the array.
arytextfile = lineoftext.Split(",")
'dunno whether this is the best way to do it, but stick the array bits into the record, and then clear the array to start again.
PetArray(totalRecCount).custName = arytextfile(0)
PetArray(totalRecCount).address = arytextfile(1)
PetArray(totalRecCount).petType = arytextfile(2)
PetArray(totalRecCount).vacced = arytextfile(3)
totalRecCount += 1
Array.Clear(arytextfile, 0, arytextfile.Length)
Loop
For i = 0 To PetArray.GetUpperBound(0)
If PetArray(i).vacced = "No" Then
lstVaccinated.Items.Add(PetArray(i).vacced)
lstCustomer.Items.Add(PetArray(i).custName)
lstAddress.Items.Add(PetArray(i).address)
lstPetType.Items.Add(PetArray(i).petType)
totNotVac += 1
lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
End If
Next
Catch ex As Exception
MsgBox("Something went wrong with the file")
End Try
PetFile.Close()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
End Class
And one line from the patient.txt file:
Richard Gere,16 Sunset Blvd,Gerbil,No
I hope this isn't out of place.
Regards,
Damian
If you want to use Streams be aware that they need to be disposed.
File.ReadAllLines returns an array of lines. Since the array is initialized where it is declared we don't need to specify a size.
If you use List(Of T) you do not have to know in advance the number of elements in the list. Avoids the limitation of array.
Using a For Each avoids having to use the size. The small c following "," tells the compiler that this is a Char which is what .Split is expecting. If you had Option Strict On, which you always should, you would have seen an error. You add items to the list by creating a New PetsRecord. The parametrized Sub New receives the values and sets the properties.
Don't change the display in the label on each iteration. Use an interpolated string (preceded by a $) which allows embedded variables surrounded by braces { }. It is not necessary to change the number to a string as it is implied by the interpolator. (Available in VS2015 and later)
Public Structure PetsRecord
Public Property custName As String
Public Property address As String
Public Property petType As String
Public Property vacced As String
Public Sub New(name As String, add As String, pType As String, vac As String)
custName = name
address = add
petType = pType
vacced = vac
End Sub
End Structure
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines = File.ReadAllLines("patients.txt")
Dim lstPet As New List(Of PetsRecord)
For Each line In lines
Dim splits = line.Split(","c)
lstPet.Add(New PetsRecord(splits(0), splits(1), splits(2), splits(3)))
Next
Dim totNotVac As Integer
For Each pet In lstPet
If pet.vacced = "No" Then
lstVaccinated.Items.Add(pet.vacced)
lstCustomer.Items.Add(pet.custName)
lstAddress.Items.Add(pet.address)
lstPetType.Items.Add(pet.petType)
totNotVac += 1
End If
Next
lblVacTotal.Text = $"The total number of unvaccinated animals is {totNotVac}"
End Sub
If you don't need the 'PetsRecord' array to store data, take a look at the following code:
Dim totNotVac As Integer
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
File.ReadAllLines("your text file path").ToList().ForEach(Sub(x)
lstVaccinated.Items.Add(x.Split(","c)(0))
lstCustomer.Items.Add(x.Split(","c)(1))
lstAddress.Items.Add(x.Split(","c)(2))
lstPetType.Items.Add(x.Split(","c)(3))
totNotVac += 1
End Sub)
lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
End Sub

(VB.NET) display the lower half of a textfile to a listbox

I have to make a application that organizes a list of runners and their teams. In the following text file, I have to remove the top half of the text file (the top half being the listed teams) and display only the bottom half (the runners)in a listbox item.
The Text file:
# School [School Code|School Name|Coach F-Name|Coach L-Name|AD F-Name|AD L Name]
WSHS|Worcester South High School|Glenn|Clauss|Bret|Zane
WDHS|Worcester Dorehty High School|Ellsworth|Quackenbush|Bert|Coco
WBCHS|Worcester Burncoat High School|Gail|Cain|Kevin|Kane
QRHS|Quabbin Regional High School|Bob|Desilets|Seth|Desilets
GHS|Gardner High School|Jack|Smith|George|Fanning
NBHS|North Brookfield High School|Hughe|Fitch|Richard|Carey
WHS|Winchendon High School|Bill|Nice|Sam|Adams
AUBHS|Auburn High School|Katie|Right|Alice|Wonderland
OXHS|Oxford High School|Mary|Cousin|Frank|Daughter
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
101|WSHS|Sanora|Hibshman
102|WSHS|Bridgette|Moffitt
103|WSHS|Karine|Chunn
104|WSHS|Shanita|Wind
105|WSHS|Fernanda|Parsell
106|WSHS|Albertha|Baringer
107|WSHS|Carlee|Sowards
108|WDHS|Maisha|Kleis
109|WDHS|Lezlie|Berson
110|WDHS|Deane|Rocheleau
111|WDHS|Hang|Hodapp
112|WDHS|Zola|Dorrough
113|WDHS|Shalon|Mcmonigle
I have some code that reads each row from the text file as an array and uses boolean variables to determine where to end the text file. This worked with displaying only the teams, which I've managed to do. But I now need to do the opposite and display only the players, and I'm a bit stumped.
My Code:
Private Sub btnLoadTeams_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTeam.Click
' This routine loads the lstTeam box from an ASCII .txt file
' # School [School Code | Name | Coach F-Name| Coach L-Name | AD F-Name | AD L-Name]
Dim strRow As String
Dim bolFoundCode As Boolean = False
Dim bolEndCode As Boolean = False
Dim bolFoundDup As Boolean = False
Dim intPosition As Integer
Dim intPosition2 As Integer
Dim strTeamCodeIn As String
Dim textIn As New StreamReader( _
New FileStream(txtFilePath.Text, FileMode.OpenOrCreate, FileAccess.Read))
' Clear Team listbox
lstTeam.Items.Clear()
btnDeleteRunner.Enabled = True
Do While textIn.Peek <> -1 And Not bolEndCode
Me.Refresh()
strRow = textIn.ReadLine.Trim
If Not bolFoundCode Then
If "# SCHOOL " = UCase(Mid(strRow, 1, 9)) Then
bolFoundCode = True
End If
Else
If Mid(strRow, 1, 2) <> "# " Then
For Each item As String In lstTeam.Items
intPosition = InStr(1, strRow, "|")
strTeamCodeIn = Mid(strRow, 1, intPosition - 1)
intPosition2 = InStr(1, item, strTeamCodeIn)
If intPosition2 > 0 Then
bolFoundDup = True
MsgBox("Found Duplicate School Code: " & strTeamCodeIn)
End If
Else
bolEndCode = True
Next
If Not bolFoundDup Then
lstTeam.Items.Add(strRow)
Else
lstTeam.Items.Add("DUPLICATE School Code: " & strRow)
lstTeam.Items.Add("Please correct input file and reload teams")
bolEndCode = True
End If
End If
End If
Loop
End Sub
Ive put bolEndCode = True in between the part that reads the mid section of the text file, but all Ive managed to display is the following in the listbox:
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
Any help or hints on how I would display just the runners to my "lstPlayers" listbox would be greatly appreciated. I'm a beginner programmer and We've only just started learning about reading and writing arrays in my .NET class.
First I made 2 classes, one Runner and one School. These have the properties available in the text file. As part of the class I added a function that overrides .ToString. This is for he list boxes that call .ToString for display.
Next I made a function that reads all the data in the file. This is very simple with the File.ReadLines method.
Then I created 2 variables List(Of T) T stands for Type. Ours Types are Runner and School. I used List(Of T) instead of arrays because I don't have to worry about what the size of the list is. No ReDim Preserve, just keep adding items. The FillList method adds the data to the lists. First I had to find where the schools ended and the runners started. I used the Array.FindIndex method which is a bit different because the second parameter is a predicate. Check it out a bit. Now we know the indexes of the lines we want to use for each list and use a For...Next loop. In each loop an instance of the class is created and the properties set. Finally the new object is added to the the list.
Finally we fill the list boxes with a simple .AddRange and the lists.ToArray. Note that we are adding the entire object, properties and all. The neat thing is we can access the properties from the listbox items. Check out the SelectedIndexChanged event. You can do the same thing with the Runner list box.
Sorry, I couldn't just work with your code. I have all but forgotten the old vb6 methods. InStr, Mid etc. It is better when you can to use .net methods. It makes your code more portable when the boss says "Rewrite the whole application in C#"
Public Class Runner
Public Property BibNum As Integer
Public Property SchoolCode As String
Public Property FirstName As String
Public Property LastName As String
Public Overrides Function ToString() As String
'The listbox will call .ToString when we add a Runner object to determin what to display
Return $"{FirstName} {LastName}" 'or $"{LastName}, {FirstName}"
End Function
End Class
Public Class School
Public Property Code As String
Public Property Name As String
Public Property CoachFName As String
Public Property CoachLName As String
Public Property ADFName As String
Public Property ADLName As String
'The listbox will call .ToString when we add a School object to determin what to display
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Private Runners As New List(Of Runner)
Private Schools As New List(Of School)
Private Function ReadData(path As String) As String()
Dim lines = File.ReadLines(path).ToArray
Return lines
End Function
Private Sub FillLists(data As String())
Dim location = Array.FindIndex(data, AddressOf FindRosterLine)
'The first line is the title so we don't start at zero
For index = 1 To location - 1
Dim SplitData = data(index).Split("|"c)
Dim Schl As New School
Schl.Code = SplitData(0)
Schl.Name = SplitData(1)
Schl.CoachFName = SplitData(2)
Schl.CoachLName = SplitData(3)
Schl.ADFName = SplitData(4)
Schl.ADLName = SplitData(5)
Schools.Add(Schl)
Next
For index = location + 1 To data.GetUpperBound(0)
Dim SplitData = data(index).Split("|"c)
Dim Run As New Runner
Run.BibNum = CInt(SplitData(0))
Run.SchoolCode = SplitData(1)
Run.FirstName = SplitData(2)
Run.LastName = SplitData(3)
Runners.Add(Run)
Next
End Sub
Private Function FindRosterLine(s As String) As Boolean
If s.Trim.StartsWith("# Roster") Then
Return True
Else
Return False
End If
End Function
Private Sub FillListBoxes()
Dim arrRunners As Runner() = Runners.ToArray
Dim arrSchools As School() = Schools.ToArray
ListBox1.Items.AddRange(arrSchools)
ListBox2.Items.AddRange(arrRunners)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim arrRunner = ReadData("Runners.txt")
FillLists(arrRunner)
FillListBoxes()
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim Schl = DirectCast(ListBox1.SelectedItem, School)
TextBox1.Text = Schl.CoachLName
TextBox2.Text = Schl.Code
End Sub

Working with Array As New Object does not work

my VBA-code is making trouble. I made a Class module called "clsColl" with the Properties. When i declare a variable as "clsColl" everything working fine, but when i declare an array as "clsColl" i get an error
"Object variable or With block variable not set", if i use this array in another sub, which i called in the first sub.
I made a short example with just the code in it which making trouble.
First my class module "clsColl"
Option Explicit
Public name As String
Public weight as single
Now the code which is working
Sub workingA()
Dim persona As New clsColl
Call workingB(persona)
End Sub
Sub workingB(persona As cls Coll)
persona.name = "phil"
persona.weight = 100
End Sub
Now the code which is not working
Sub failingA()
Dim persona() As New clsColl
ReDim persona(1 to 5)
Call failingB(persona)
End Sub
Sub failingB(persona() As cls Coll)
persona(1).name = "phil"
persona(1).weight = 100
End Sub
I get an error, just by changing my code from using a variable to using an array.
Now i get an error Object variable or With block variable not set" with the second code, but i don't know why. I want to know why using an array as an object is making trouble like this, while using a normal variable is working fine.
Your code line
Dim persona As New clsColl
is a combination of
Dim persona As clsColl
If persona Is Nothing Then Set persona = New clsColl
and it is bad practice using that combining syntax at all, at least in my opionion.
Now for the array this cannot work anymore as each array item must be Set to be an clsColl object first:
Sub notMorefailingA()
Dim persona() As clsColl
Dim i As Integer
ReDim persona(1 To 5)
For i = 1 To 5
Set persona(i) = New clsColl
Next
Call notMorefailingB(persona)
End Sub
Sub notMorefailingB(persona() As clsColl)
persona(1).name = "phil"
persona(1).weight = 100
End Sub
You have nothing in the array you need to populate the array with classes. Your Dim wont use the new keyword, you'll create new classes and add them into the array.
Sub test1()
Dim d As New clsDimension
Dim arrDimensions(5) As clsDimension
Set arrDimensions(0) = d
arrDimensions(0).Breadth = 100
arrDimensions(0).Depth = 200
End Sub
or in a similar approach to your post
A class for the array, like so, clsDimensionArray
Private arrDimensions() As clsDimension
Public Property Get ArrItems(x As Long) As clsDimension
Set ArrItems = arrDimensions(x)
End Property
Public Sub Create(lngSize As Long)
Dim l As Long
Dim d As clsDimension
ReDim arrDimensions(lngSize - 1)
For l = 0 To UBound(arrDimensions)
Set d = New clsDimension
Set arrDimensions(l) = d
Set d = Nothing
Next l
End Sub
and using like so
Sub test1()
Dim arrDimensions As New clsDimensionArray
arrDimensions.Create (100)
arrDimensions.ArrItems(90).Depth = 50
arrDimensions.ArrItems(90).Breadth = 100
End Sub
Keeps it nice and tidy :o)

Adding Item to Array (VB 2008)

The objective of the program is to interpret hockey statistics from a file using StreamReader and then display an added column of points. The following code kinda does so, however it’s ineffective in the sense that it doesn’t add the points value to the array - it separately outputs it. Looking for assistance as to how it would be possible to incorporate the points value into aryTextFile();
Dim hockeyFile, LineOfText, aryTextFile() As String
Dim i As Integer
Dim nameText(), NumberText(), goalsText(), assistsText(), GamesWonText() As String
Dim IntAssists(), IntGoals(), PointsText() As Single
hockeyFile = "C:\Users\Bob\Downloads\hockey.txt" 'state location of file
Dim objReader As New System.IO.StreamReader(hockeyFile) 'objReader can read hockeyFile
For i = 0 To objReader.Peek() <> -1 'reads each line seperately, ends when there is no more data to read
LineOfText = objReader.ReadLine 'stores seperate lines of data in HockeyFile into LineofText
aryTextFile = LineOfText.Split(",") 'takes lines and converts data into array
Name = aryTextFile(0) 'first piece of data in lines of text is the name
nameText(i) = aryTextFile(0)
If nameText(0) = "Name" Then
TextBox1.Text = LineOfText & ", Points." & vbCrLf 'displays first line fo text and adds "Points" label
End If
If Name <> "Name" Then 'when second line starts, then begin to intepret data
NumberText(i) = aryTextFile(1)
assistsText(i) = aryTextFile(2) 'assists are in third value of array
goalsText(i) = aryTextFile(3) 'goals are in fourth value of array
GamesWonText(i) = aryTextFile(4)
IntAssists(i) = Val(assistsText(i)) 'since our assists value is a string by default, it must be converted to a integer
IntGoals(i) = Val(goalsText(i)) 'since our goals value is a string by default, it must be converted to a integer
PointsText(i) = (IntGoals(i) * 2) + (IntAssists(i)) 'goals are two points, assists are one point
TextBox1.Text = TextBox1.Text & NumberText(i) & assistsText(i) & goalsText(i) & GamesWonText(i) & PointsText(i) & vbCrLf 'Displays points as last value in each line
End If
Next i
This should get you pretty close:
It'll need extra validation. It doesn't take into account whatever value you have between the name and the goals.
Private Sub ProcessHockeyStats()
Try
Dim inputFile As String = "c:\temp\hockey.txt"
Dim outputFile As String = "c:\temp\output.txt"
If Not File.Exists(inputFile) Then
MessageBox.Show("Missing input file")
Return
End If
If File.Exists(outputFile) Then
File.Delete(outputFile)
End If
Dim lines() As String = File.ReadAllLines(inputFile)
Dim output As List(Of String) = New List(Of String)
Dim firstLine As Boolean = True
For Each line As String In lines
Dim values() As String = line.Split(","c)
Dim points As Integer
If firstLine Then
output.Add("Name, Assists, Goals, Points")
firstLine = False
Else
'needs validation for values
points = CInt(values(1) * 2) + CInt(values(2))
output.Add(String.Concat(line, ",", points))
End If
Next
File.WriteAllLines("c:\temp\outfile.txt", output)
Catch ex As Exception
MessageBox.Show(String.Concat("Error occurred: ", ex.Message))
End Try
End Sub
VS2008 is ancient, especially when later versions of Visual Studio are free. I felt like showing an implementation using more-recent code. Like others, I strongly support building a class for this. The difference is my class is a little smarter, using the Factory pattern for creating instances and a Property to compute Points as needed:
Public Class HockeyPlayer
Public Property Name As String
Public Property Number As String
Public Property Assists As Integer
Public Property Goals As Integer
Public Property Wins As Integer
Public ReadOnly Property Points As Integer
Get
Return (Goals * 2) + Assists
End Get
End Property
Public Shared Function FromCSVLine(line As String) As HockeyPlayer
Dim parts() As String = line.Split(",")
Return New HockeyPlayer With {
.Name = parts(0),
.Number = parts(1),
.Assists = CInt(parts(2)),
.Goals = CInt(parts(3)),
.Wins = CInt(parts(4))
}
End Function
End Class
Dim hockeyFile As String = "C:\Users\Bob\Downloads\hockey.txt"
Dim players = File.ReadLines(hockeyFile).Skip(1).
Select(Function(line) HockeyPlayer.FromCSVLine(line)).
ToList() 'ToList() is optional, but I included it since you asked about an array
Dim result As New StringBuilder("Name, Number, Assists, Goals, Wins, Points")
For Each player In players
result.AppendLine($"{player.Name}, {player.Number}, {player.Assists}, {player.Goals}, {player.Wins}, {player.Points}")
Next player
TextBox1.Text = result.ToString()
I was gonna give you VS 2008 version afterward, but looking at this, the only thing here you couldn't do already even by VS 2010 was string interpolation... you really should upgrade.
Parallel arrays are really not the way to handle this. Create a class or structure to organize the data. Then create a list of the class. The list can be set as the DataSource of a DataGridView which will display your data in nice columns with headings matching the names of your properties in the Hockey class. You can easily order your data in the HockeyList by any of the properties of Hockey.
Public Class Hockey
Public Property Name As String
Public Property Number As String
Public Property Goals As Integer
Public Property Assists As Integer
Public Property Points As Integer
Public Property GamesWon As Integer
End Class
Private HockeyList As New List(Of Hockey)
Private Sub FillListAndDisplay()
Dim path = "C:\Users\Bob\Downloads\hockey.txt"
Dim Lines() = File.ReadAllLines(path)
For Each line As String In Lines
Dim arr() = line.Split(","c)
Dim h As New Hockey()
h.Name = arr(0)
h.Number = arr(1)
h.Assists = CInt(arr(2).Trim)
h.Goals = CInt(arr(3).Trim)
h.GamesWon = CInt(arr(4).Trim)
h.Points = h.Goals * 2 + h.Assists
HockeyList.Add(h)
Next
Dim orderedList = (From scorer In HockeyList Order By scorer.Points Ascending Select scorer).ToList
DataGridView1.DataSource = orderedList
End Sub

ProcessWindowStyle.Hidden in string array

In my VB.net project, I am trying to call up multiple programs using an array to help clean up my code.
Currently, I have this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles StartServer.Click
Dim proc As New ProcessStartInfo()
Dim prochide As New ProcessStartInfo()
prochide.WindowStyle = ProcessWindowStyle.Hidden
If CheckBox1.CheckState = 1 Then
proc.WorkingDirectory = TextBox1.Text
proc.FileName = "xserver.exe"
Process.Start(proc)
proc.FileName = "yserver.exe"
Process.Start(proc)
proc.FileName = "zserver.exe"
Process.Start(proc)
Else
prochide.WorkingDirectory = TextBox1.Text
prochide.FileName = "xserver.exe"
Process.Start(prochide)
prochide.FileName = "yserver.exe"
Process.Start(prochide)
prochide.FileName = "zserver.exe"
Process.Start(prochide)
End If
End Sub
What this does is allows me to hide the windows so they show up in task manager but the windows don't actually show up.
However, I would prefer to switch with this code or something similar to clean it up:
Dim servers(0 To 2) As String
servers(0) = "xserver.exe"
servers(1) = "yserver.exe"
servers(2) = "zserver.exe"
Then I can simplify the code:
Dim directory As String = TextBox1.Text
For Each fileName As String In servers
Next
However, I cannot figure out how to hide the windows in an array, since the .WindowStyle = ProcessWindowStyle.Hidden does not seem to work with array strings. Is there another way I can do this?Changing the method is fine, I just want to try to clean up the code since it seems a bit bulky right now.
Okay so I've finally checked this out, and this works for me:
Public Class Form1
Dim servers() As String = New String() {"cmd.exe|1", "cmd.exe|1", "cmd.exe|1"}
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim directory As String = TextBox1.Text
Dim prochide As New ProcessStartInfo()
prochide.WorkingDirectory = directory
For Each fileName As String In servers
Dim FileOptions() As String = Split(fileName, "|")
prochide.FileName = FileOptions(0)
prochide.WindowStyle = CType(FileOptions(1), ProcessWindowStyle)
Process.Start(prochide)
Next
End Sub
End Class
When using New String() you cannot declare the array with a limit. So that was our problem. :)
So instead of Dim servers(3)... or Dim servers(0 To 2)... you have to use Dim servers()...

Resources