Visual Basic school project - vba

Visual Basic is not my primary language and I am trying to help my son with a school project and failing miserably. The program is suppose to read a file, create an ID and save it to disk. Everything works fine except for the last 2 procedures, determine the minimum swim time, (It does that) but I am trying to assign the firstName of the user to the fastestSwimmer and in the last procedure display the winner and min time.
the file it is reading is just a text file with formatted as FirstName,Surname,Age and Gender.
My fastest Swimmer is always passing a null reference to the method. Any help would be greatly appreciated.
this is the whole program:
Public Class Form1
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
Dim firstName(5) As String
Dim surname(5) As String
Dim age(5) As String
Dim gender(5) As String
Dim swimID(5) As String
Dim time(5) As Single
Dim fastestSwimmer As String
Dim minTime As Single
'Call Procedures
Call GetDetails(firstName, surname, age, gender)
Call CalcSwimID(swimID, firstName, surname, age, gender)
Call RaceTimes(time, firstName, surname)
Call CalcWinner(time, firstName, fastestSwimmer, minTime)
'Call WinnersCircle(fastestSwimmer, minTime)
End Sub
'Get details from reading a file
Private Shared Sub GetDetails(ByVal firstName As String(), ByVal surname As String(), ByVal age As String(), ByVal gender As String())
Dim filename As String
filename = "C:/Users/rk/source/repos/CleanFolder/SwimersChampionShip/details.txt"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 5
Input(1, firstName(counter))
Input(1, surname(counter))
Input(1, age(counter))
Input(1, gender(counter))
Next
FileClose(1)
End Sub
'Create a Swimmers ID and save it back to disk
Private Shared Sub CalcSwimID(ByRef swimID As String(), ByRef firstName As String(), ByRef surname As String(), ByRef Age As String(), ByRef gender As String())
Dim genderAscii(5) As Integer
Dim firstCharacter(5) As String
For counter = 1 To 5
firstCharacter(counter) = firstName(counter).Substring(0, 1)
genderAscii(counter) = Asc(gender(counter))
swimID(counter) = genderAscii(counter) & "-" & firstCharacter(counter) & surname(counter) & "-" & Age(counter)
Next
Dim savedFile As String
savedFile = ("C:/Users/rk/source/repos/CleanFolder/SwimersChampionShip/competitorsID.txt")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 5
PrintLine(1, swimID(counter))
Next
FileClose(1)
End Sub
' Gets the race times by input box
Private Shared Sub RaceTimes(ByRef time As Single(), ByRef firstName As String(), ByRef surname As String())
For counter = 1 To 5
time(counter) = InputBox(" Please enter the swim times for " & firstName(counter) & " " & surname(counter))
Next
'MsgBox(time)
End Sub
'This will calculate the winner
Private Sub CalcWinner(ByRef time As Single(), ByRef firstName As String(), ByVal fastestSwimmer As String, ByRef minTime As Single)
'MsgBox(time(1))
minTime = time(1) And fastestSwimmer = firstName(1)
For counter = 2 To 5
If time(counter) < minTime Then
minTime = time(counter) And fastestSwimmer = firstName(counter)
End If
Next
'MsgBox(minTime)
End Sub
' Displays winner of the race to the winners circle, Gold medal will be sent by mail!
Private Sub WinnersCircle(ByRef fastestSwimmer As String, ByRef minTime As Single)
ListBox1.Items.Add("Congradulations " & fastestSwimmer & " you are the winner your time was " & minTime & " seconds. A new world record!")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
End Class

In the CalcWinner method you use AND in the wrong way:
Private Sub CalcWinner(ByRef time As Single(), ByRef firstName As String(), ByVal
fastestSwimmer As String, ByRef minTime As Single)
'MsgBox(time(1))
minTime = time(1)
fastestSwimmer = firstName(1)
For counter = 2 To 5
If time(counter) < minTime Then
minTime = time(counter)
fastestSwimmer = firstName(counter)
End If
Next
'MsgBox(minTime)
End Sub
When you write
minTime = time(1) And fastestSwimmer = firstName(1)
VB will ADD the first time ( time(1)) and fastestSwimmer = firstName(1) which is 0 because fastestSwimmer is not equal to firstName(1) so that evaluates to 0

Related

VB Calculate max jumps

I am reading a .csv file in my FindMaxJumps method I am trying to make a loop to find the highest amount of jumps and set that to the highest max jumps. I have jumps set up as a String to read the csv file but thought I need to convert to a single or integer to make the comparison for all the users:
complete code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
'Variables for each user
Dim entryID(11) As String
Dim location(11) As String
Dim forename(11) As String
Dim surname(11) As String
Dim jumps(11) As String
Dim bibValues(11) As String
Dim maxJumps As Single
Dim jumpsCounter As Single
Call LoadAthletes(entryID, location, forename, surname, jumps)
Call CreateBibValues(bibValues, forename, surname, location)
Call FindMaxJumps(jumpsCounter, maxJumps, forename, surname, jumps)
End Sub
'Get details from reading a file
Private Sub LoadAthletes(ByRef entryID As String(), ByRef location As String(), ByRef forname As String(), ByRef surname As String(), ByRef jumps As String())
Dim filename As String
filename = "C:\Users\rk\source\repos\Scottish Jumping Jax\athletes.csv"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 11
Input(1, entryID(counter))
Input(1, location(counter))
Input(1, forname(counter))
Input(1, surname(counter))
Input(1, jumps(counter))
Next
FileClose(1)
End Sub
Private Sub CreateBibValues(ByVal bibValues As String(), ByVal forename As String(), ByVal surname As String(), ByVal location As String())
Dim locationAscii(11) As Integer
Dim firstCharacter(11) As String
For counter = 1 To 11
firstCharacter(counter) = location(counter).Substring(0, 1)
locationAscii(counter) = Asc(location(counter))
bibValues(counter) = firstCharacter(counter) & surname(counter) & locationAscii(counter)
Next
Dim savedFile As String
savedFile = ("C:\Users\rk\source\repos\Scottish Jumping Jax\bibValues.csv")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 11
PrintLine(1, bibValues(counter))
Next
FileClose(1)
End Sub
Private Sub FindMaxJumps(ByVal jumpsCounter As Single, ByVal maxJumps As Single, ByVal forename As String(), ByVal surname As String(), ByVal jumps As String())
End Sub
End Class
the corrected code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Variables for each user
Dim entryID(11) As String
Dim location(11) As String
Dim forename(11) As String
Dim surname(11) As String
Dim jumps(11) As Integer
Dim bibValues(11) As String
Dim maxJumps As Integer
'Define Calls and Functions
Call LoadAthletes(entryID, location, forename, surname, jumps)
Call CreateBibValues(bibValues, forename, surname, location)
Call FindMaxJumps(maxJumps, jumps)
Call DisplayMaxJumpers(maxJumps, forename, surname, jumps)
Call TallyAthletes()
End Sub
'Get details from reading a file
Private Sub LoadAthletes(ByRef entryID As String(), ByRef location As String(), ByRef forname As String(), ByRef surname As String(), ByRef jumps As Integer())
Dim filename As String
filename = "C:\Users\rk\source\repos\Scottish Jumping Jax\athletes.csv"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 11
Input(1, entryID(counter))
Input(1, location(counter))
Input(1, forname(counter))
Input(1, surname(counter))
Input(1, jumps(counter))
Next
FileClose(1)
End Sub
'Creates the BibValues and saves it to disk
Private Sub CreateBibValues(ByVal bibValues As String(), ByVal forename As String(), ByVal surname As String(), ByVal location As String())
'local var to determine Ascii converstion and what character to convert
Dim locationAscii(11) As Integer
Dim firstCharacter(11) As String
'Loop to assign Bib Values
For counter = 1 To 11
firstCharacter(counter) = forename(counter).Substring(0, 1)
locationAscii(counter) = Asc(location(counter))
bibValues(counter) = firstCharacter(counter) & surname(counter) & locationAscii(counter)
Next
'Save bibValues.csv to disk
Dim savedFile As String
savedFile = ("C:\Users\rk\source\repos\Scottish Jumping Jax\bibValues.csv")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 11
PrintLine(1, bibValues(counter))
Next
FileClose(1)
End Sub
'Function to find max jumps
Public Function FindMaxJumps(ByVal maxJumps As Integer, ByVal jumps As Integer())
maxJumps = jumps(1)
For counter = 2 To 11
If jumps(counter) > maxJumps Then
maxJumps = jumps(counter)
End If
Next
MsgBox(maxJumps)
Return maxJumps
End Function
'Determines if current number of jumps equals max jumps and displays forename and surname
Private Sub DisplayMaxJumpers(ByVal maxJumps As Integer, ByVal forename As String(), ByVal surname As String(), ByVal jumps As Integer())
End Sub
' Displays how many finalists by location
Private Sub TallyAthletes()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class

Edit Button: Conversion from string "name" in the datagrid view

I'm trying to edit a selected row from my Datagridview. When I try to change something in the textboxes, I get an error message for the first name and last name textboxes, stating: "Conversion from string "name" to type integer is not valid. If anyone could help me figure out what I'm doing wrong it would be greatly appreciated.
Dim dbo As New OwnersDataContext
Dim theowner As New Owners
Dim index As Integer
Private Sub DGV1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV1.CellContentClick
index = e.RowIndex
Dim selectedRow As DataGridViewRow
selectedRow = DGV1.Rows(index)
txtid.Text = selectedRow.Cells(0).Value.ToString
txtfname.Text = selectedRow.Cells(1).Value.ToString
txtlname.Text = selectedRow.Cells(2).Value.ToString
txtaddress.Text = selectedRow.Cells(3).Value.ToString
txtcity.Text = selectedRow.Cells(4).Value.ToString
cbostates.SelectedItem = selectedRow.Cells(5).Value.ToString
txtzipcode.Text = selectedRow.Cells(6).Value.ToString
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If DGV1.SelectedRows.Count < 0 Then
MessageBox.Show("Select owner")
Else
**If theowner.Update(txtid.Text, txtfname.Text, txtlname.Text, txtaddress.Text, txtcity.Text, CStr(cbostates.SelectedItem), txtzipcode.Text) = 0** Then
MessageBox.Show("New Owner could not be saved to database. Please check input.")
Else
Me.Close()
'refill the tbl with the updated
Dim q = From o In dbo.Owners
Select o.Owner_ID, o.Owner_FirstName, o.Owner_LastName, o.Address, o.City, o.State, o.ZipCode
DGV1.DataSource = q
End If
End If
End Sub
Added the update method from my class
Public Function Update(ByVal pOwnerID As Integer, ByVal pfname As String,
ByVal plname As String, ByVal pAddress As String, ByVal pCity As String, ByVal pState As String, ByVal pZipCode As Integer) As Integer
Return mytableadapter.Update(pfname, plname, pAddress, pCity, pState, pZipCode, pOwnerID) > 0
End Function

Beginner doing an OOP Project vb.net

Alright, so I have edited my code and now when I'm trying to run it I'm getting this error.
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "Holden 308" to type 'Integer' is not valid.
Additional information: Conversion from string "JD Catepillar Track" to type 'Integer' is not valid.
So both errors are happening in the HeavyStockItem class with the overloading New classes. Wondering if anyone can help me out with understanding why it's doing that.
Option Strict On
Public Class Form1
Dim StockItem1 As StockItem
Dim StockItem2 As CarEngine
Dim StockItem3 As CarEngine
Dim StockItem4 As StockItem
Dim StockItem5 As HeavyStockItem
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StockItem1 = New StockItem("Screwdriver Set", 42)
StockItem2 = New CarEngine(8025, "Madza B6T", 1252, 800, "Z4537298D")
'StockItem3 = New CarEngine("Holden 308", 958, 1104, "P74623854S")
StockItem4 = New StockItem(8002, "Trolley Jack", 127)
'StockItem5 = New HeavyStockItem("JD Catepillar Track", 3820, 2830)
End Sub
Private Sub btnListStock_Click(sender As Object, e As EventArgs) Handles btnListStock.Click
txtOutput.Clear()
ShowOutput(StockItem1)
ShowOutput(StockItem2)
'ShowOutput(StockItem3)
ShowOutput(StockItem4)
'ShowOutput(StockItem5)
End Sub
Public Sub ShowOutput(ByVal Output As StockItem)
txtOutput.Text &= Output.Print()
txtOutput.Text &= vbCrLf
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnd.Click
End
End Sub
End Class
Public Class StockItem
Friend CostPrice As Integer
Friend LastStockNumber As Integer
Friend StockNumber As Integer
Friend Description As String
Friend Shared LastStockItem As Integer = 10000
Overridable Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, Description As String, ByVal CostPrice As Integer)
Me.New(Description, CostPrice)
Me.StockNumber = StockNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
Me.Description = Description
Me.CostPrice = CostPrice
End Sub
Public Sub GetCostPrice()
End Sub
End Class
Public Class HeavyStockItem
Inherits Assessment3.StockItem
Friend Weight As Integer
Public Function GetWeight() As String
Return Me.GetWeight
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(StockNumber, Description, CostPrice)
Me.Weight = Weight
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(Description, CostPrice, Weight)'' Where the error is occurring
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Public Class CarEngine
Inherits Assessment3.HeavyStockItem
Friend EngineNumber As String
Overrides Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Result &= "Weight: " & Weight
Result &= vbCrLf
Result &= "Engine Number: " & EngineNumber
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(StockNumber, Description, CostPrice, Weight)
Me.EngineNumber = EngineNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(Description, CostPrice, Weight)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Any help provided would be great. Just thought it'd be easier to provide the full code instead of just putting only the little bits that I really needed, incase if people asked about the other parts of the code. Thanks for reading and providing help if you provided help.
Since your code was confusing to me I relied mostly on the exception.
It basically says that it cant convert the string into an integer. Here's something that could cause the same problem.
Dim Number As String = "10"
'Few Lines of code.
Number = 11
whats basically happening is that when you declare a variable as a string the value of it HAS to be in double quotes as you see when it was declared. Now then we try to change the value to 11 while adding no double quotes, therefor it thought you were changing it to an integer and gave the error.
I looked through the code and saw this, maybe this is causing it:
Me.Description = Description <--- No quotes!!!
I'm probably wrong though since i didn't really understand the code.

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].

Running Different Processes In Multiple Threads Without Overlapping In VB.NET 2

I have a sub-procedure which I want to run a different process, depending on what is currently running. I thought the easiest way to do this was by using an ArrayList of each of the campaign details & adding an 'Inuse' field to check to see if the Inuse field is set to 0 or 1. The problem that I have is that when running the process it is all happening at once & the integer hasn't been changed before the next thread kicks in so my threads are running the same campaigns.
I tried to avoid the problem by adding a Thread.Sleep(100) delay inbetween starting threads but this led to exactly the same problem.
Here's an example of what I am trying to do:
Imports System.Threading
Public Class Form1
Private Campaigns As New ArrayList
Private ProcessRunning As Boolean = False
Friend StopProcess As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i = 0 To Campaigns.Count - 1
Dim objNewThread As New Thread(AddressOf RunProcess)
objNewThread.IsBackground = True
objNewThread.Start()
Next
End Sub
Private Sub UpdateCells(ByVal CampID As Integer, ByVal Column As String, ByVal newText As String)
Dim CellItemNum As Integer
If Column = "Status" Then CellItemNum = 4
DataGridView2.Rows(CampID).Cells.Item(CellItemNum).Value = newText
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To 10
Campaigns.Add({Campaigns.Count(), "Campaign " & i, "Keywords " & i, "Link " & i, 5, True, 0, 0})
Next
DataGridView2.Rows.Clear()
For Each Campaign In Campaigns
DataGridView2.Rows.Add(New String() {Campaign(1), Campaign(2), Campaign(3), Campaign(6), ""})
Next
End Sub
Private Sub RunProcess()
' Set Variables
Dim CampID As Integer
Dim CampName As String
Dim Keywords As String
Dim Link As String
Dim CheckEvery As Integer
Dim OkToUse As Boolean
Dim Sent As Integer
' Find A Free Campaign
For i As Integer = 0 To Campaigns.Count - 1
' Check If Inuse
If Campaigns(i)(7) = 1 Then Continue For Else Campaigns(i)(7) = 1 ' This Line Sets Campaign To Inuse
' Most of the time only campaign(0) and campaign(1) are selected & multiple threads are running them instead of choosing unique campaigns
' Set Campaign Details
CampID = Campaigns(i)(0)
CampName = Campaigns(i)(1)
Keywords = Campaigns(i)(2)
Link = Campaigns(i)(3)
CheckEvery = Campaigns(i)(4)
OkToUse = Campaigns(i)(5)
Sent = Campaigns(i)(6)
' Start Process
UpdateCells(CampID, "Status", "Looking Up New Links (" & CampID & ")")
Exit For
Next
While StopProcess = False
Thread.Sleep(1000)
UpdateCells(CampID, "Status", "Running Process (" & CampID & ")")
Thread.Sleep(1000)
For i = 0 To CheckEvery
UpdateCells(CampID, "Status", "Re-Checking In " & (CheckEvery - i) & " Seconds")
Thread.Sleep(1000)
Next
End While
' Closing Processes
Campaigns(CampID)(7) = 0
End Sub
End Class
You can use SyncLock to force your threads to wait.
class level so all threads access same lock
private myLock as new Object
Then use syncLock when you start your process and end it when you are done.
SyncLock myLock
'process code here
End SyncLock
More MSDN info on the subject
Try looking into QueueUserWorkItem():
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
For i = 0 To Campaigns.Count - 1
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf RunProcess), Campaigns[i])
Next
End Sub
Then change the RunProcess() method to include the Campaign object sent in by the work item:
Private Sub RunProcess(ByVal o As System.Object)
' Process the Campaign
Dim campaign As Campaign = Ctype(o, Campaign)
End Sub
There will be no need for inuse, plus threads will be managed by the managed ThreadPool!