Accesing a class with properties from another class returns null values - vb.net

I am making an application that reads values from a meter that is connected to my computer via a serial cable. When i press a button i send a command to the meter and after a few miliseconds i get a response back from the meter with the answer.
I am saving these values to a class that has properties init, so that i can access these values from anywhere.
So my problem is that when i try to get the values back it returns a 'nothing value', and its probably from the initialization i have that has a 'New' like this'Dim clsSavedValues As New clsSavedValues', so when i try to get the values from that property class i create a new instanse and that instanse is empty if am not mistaken.
Ill post the code below but here is how the code flows:
I have 3 classes. MainClass, ProtocolClass, PropertiesClass.
From main i call a method inside ProtocolClass, and that method sends a command to the meter. after a few miliseconds i get a call back inside ProtocolClass anf this method is called 'Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived' and it saves that return value to the PropertiesClass.
And after the DataReceived method is finished i go back to the MainClass and call another method to get the values from the PropertiesClass that i just saved but they return null. I know they are saved correctly because i can access them if i call them from within the ProtocolClass. But they are null from MainClass.
Here is my code:
MainClass
'Here i call the ProtocolClass
Private Sub btnGetLastTransaction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetLastTransaction.Click
clsProtocol.GetLastTransaction(1, Integer.Parse(tbxTransactionPosition.Text))
End Sub
'Here i try to read the valies from PropertiesClass
Public Sub RetrieveMeterSerialNumber()
Dim clsSavedValues As New clsSavedValues
lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber
End Sub
ProtocolClass
Public Sub GetLastTransaction(ByVal destinationAddress As String, ByVal transactionNum As Integer)
clsSavedValues = New clsSavedValues 'Creating Instance of the properties class
Try
Dim v_bodyOfMessage As [Byte]() = {ASCIItoHEX("G"), _
ASCIItoHEX("r")}
Dim v_bytearray As [Byte]() = ConstructCommand(v_bodyOfMessage)
SendCommand(v_bytearray)
Catch ex As Exception
Console.WriteLine("Meter serial number button click exception: {0}", ex)
End Try
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
If comOpen Then
Try
ReDim rx(rxPacketSize)
Console.WriteLine("RESPONSE")
For i = 0 To rxPacketSize - 1
readByte = SerialPort.ReadByte.ToString
Console.WriteLine(i.ToString & ": " & Conversion.Int(readByte).ToString)
rx(i) = Conversion.Int(readByte).ToString
If i <> 0 Then
If Convert.ToByte(rx(i)) = vDelimeterFlag(0) Then Exit For
End If
Next
DecodeResponse()
Catch ex As Exception
MsgBox("SerialPort_DataReceived Exception: " & ex.Message)
End Try
End If
End Sub
Private Sub GetMeterSerialNumber()
Dim i_startPosition As Integer = 5
Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition)
clsSavedValues.SaveMeterSerialNumber = meterSerialNumber
frmExplorer.RetrieveMeterSerialNumber() 'This is the call to the main class
End Sub
PropertiesClass
Public Property SaveMeterSerialNumber() As String
Get
Return _MeterSerialNumber
End Get
Set(ByVal meterSerialNumber As String)
_MeterSerialNumber = meterSerialNumber
End Set
End Property
I want to get the values from the PropertiesClass because ill get more than wan response from the meter and that causes thread issues and i cannot keep track with them. So i save the values in one class and then i want to access them all from that class.
Sorry for the long post, ask me anything you want for clarification

clsSavedValues in SerialPort_DataReceived() and in your Main Class RetrieveMeterSerialNumber() are two different objects (with same variable names but each 'new' create a new instance of clsSavedValues ) maybe you should pass the clsSavedValues var from protocol to Main as parameter.
Main :
Public Sub RetrieveMeterSerialNumber(clsSavedValues As clsSavedValues )
lblMeterSerialNumber.Text = clsSavedValues.SaveMeterSerialNumber
End Sub
Protocol :
Private Sub GetMeterSerialNumber()
Dim i_startPosition As Integer = 5
Dim meterSerialNumber As String = GetRemainingPortionOfString(i_startPosition)
clsSavedValues.SaveMeterSerialNumber = meterSerialNumber
frmExplorer.RetrieveMeterSerialNumber(clsSavedValues) 'This is the call to the main class
End Sub
or use a static property in your PropertiesClass

Related

using invoke in a class rather than in a form

i wrote a program reading a com port for a signal, everything was working fine, but they wanted to make the application a service so i swapped the application type to 'windows service' and created a class and put everything in the form in there and i called the class in my Main() in the startup module. the line,
Me.Invoke(New myDelegate(AddressOf UPdateVariable), New Object() {})
in the class has invoke in red saying that, "'Invoke, is not a member of Moisture.Moisture.'" and the "Me" part of that line is no longer greyed out as it was in the form. it worked before dont know what made the difference.
this is the whole code for that class
Imports System
Imports System.IO.Ports
Imports System.Net.Mime
Public Class Moisture
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
End If
Try
With serialPort
.PortName = "COM3"
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.None
.RtsEnable = True
End With
serialPort.Open()
Catch ex As Exception
End Try
End Sub
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Me.Invoke(New myDelegate(AddressOf UPdateVariable), New Object() {})
End Sub
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
If RawString.ToString().Count(Function(x As Char) x = "%"c) = 2 Then
PiTagUpdater(StringParser(RawString.ToString()))
RawString.Clear()
End If
End Sub
Public Function StringParser(RawString As String) As String
Dim Moisture = RawString
Dim value As String
Dim values As String() = Moisture.Split(New Char() {":"c})
value = values(values.Length - 1).Trim({" "c, "%"c})
Return value
End Function
Private Sub PiTagUpdater(Value As Decimal)
Try
Dim piserver As New PCA.Core.PI.PIServer(PCA.Core.Globals.Applications.Application("GENERAL").ConfigValues.ConfigValue("PI_SERVER_NAME").StringValue, PCA.Core.Globals.Applications.Application("GENERAL").ConfigValues.ConfigValue("PI_SERVER_UID").GetDeCryptedStringValue, PCA.Core.Globals.Applications.Application("GENERAL").ConfigValues.ConfigValue("PI_SERVER_PASSWD").GetDeCryptedStringValue, True)
Dim TimeStamp As DateTime = FormatDateTime(Now)
Dim RapidRingCrush = "M1:RapidRingCrush.T"
Try
piserver.WriteValue(RapidRingCrush, Value, TimeStamp)
Catch ex As Exception
MessageBox.Show("Error occured locating Pi Tag", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Application.Exit()
End Try
Catch ex As Exception
MessageBox.Show("Cannot connect to Pi Server")
End Try
End Sub
End Class
Me refers to the current object, in this case the instance of your class. Your class doesn't have an Invoke() method (like the error says), though anything that derives from System.Windows.Forms.Control does (for instance a Form).
Control.Invoke() is used to move the execution of a method to the same thread that the control was created on. This is used to achieve thread-safety.
Since you switched to a service it is fair to assume that you do not have a user interface, thus there's no need to invoke. Removing the Invoke() call and calling the method manually should be enough:
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
UPdateVariable()
End Sub
EDIT:
As LarsTech says, you also have to switch the message boxes to some kind of logging methods. A Windows Service usually runs under a different account, which means that it cannot display a user interface to the current user.

Vb .Net adding items to dictionary on button click

So I have 2 forms and a class, on my 1st form, it adds items to a dictionary and on my second form it checks if the item that is supposed to be added on dictionary is successful. But the weird thing is, in form 1, it shows that the item is added in the dictionary but in my 2nd form, when I get the count of dictionary, it produces 0 which means there's nothing in there. Hope you could help me with this.
Form 1
Public Class register
Dim acc_num As New System.Text.StringBuilder()
Dim account_info As New ArrayList()
Dim access_acc As New Accounts
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
Try
account_info.Add(fname_txt.Text & " " & lname_txt.Text)
account_info.Add("0.00")
access_acc.addAcc(account_number_lbl.Text, account_info)
MsgBox("Your account has been registered! Thank you for banking with us, your money is in good hands")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Form 2
Dim access_acc As New Accounts
Private Sub btn_process_Click(sender As Object, e As EventArgs) Handles btn_process.Click
MsgBox(access_acc.getCount().ToString)
End Sub
My Class
Public Class Accounts
Private account As New Dictionary(Of String, ArrayList)
Public Sub addAcc(ByVal account_number As String, account_info As ArrayList)
account.Add(account_number, account_info)
MsgBox(account.Count)
End Sub
Public Function getCount() As Integer
Return account.Count
End Function
End Class
I got rid of my problem by using Module(which is a C# counterpart to static) instead of Class.
Here's a reference as to what is the best method to use in a certain situation.
Module VS Classes

global variable defined in winforms not working as expected

I have a project in VB.Net that requires a global variable (a list of event log objects) throughout. This seemed simple enough, just define the variable and initialize in the Application's StartUp event, then access it throughout the application. Unfortunately, this only seems to work when there are no child processes (they have no access to the global variable) - so I'm way over my head as how to access the global variable from the child worker processes (if that is even possible).
The program starts several Test worker processes (that check multiple DB connections from different sources, remote web services from several sources, network checks, etc) w/ progress bars for each. If an error occurs during any of these tests, the error needs to be logged.
The problem is that, the program cannot log events to the Windows Event system because it won't be running under an administrator account (so logging there is not possible thanks to MS's decision to prevent logging under normal user accounts w/Vista,7,8,10), the program also can't log to a text file due to it being asynchronous and the file access contention problems (immediately logging an event to a text file won't work), so I wish to log any events/errors in memory (global variable), THEN dump it to a log file AFTER all child processes complete. Make any sense?
I created a class called AppEvent
Public Class AppEvent
Sub New()
EventTime_ = Date.Now
Level_ = EventLevel.Information
Description_ = String.Empty
Source_ = String.Empty
End Sub
Private EventTime_ As Date
Public Property EventTime() As Date
Get
Return EventTime_
End Get
Set(ByVal value As Date)
EventTime_ = value
End Set
End Property
Private Level_ As EventLevel
Public Property Level() As EventLevel
Get
Return Level_
End Get
Set(ByVal value As EventLevel)
Level_ = value
End Set
End Property
Private Description_ As String
Public Property Description() As String
Get
Return Description_
End Get
Set(ByVal value As String)
Description_ = value
End Set
End Property
Private Source_ As String
Public Property Source() As String
Get
Return Source_
End Get
Set(ByVal value As String)
Source_ = value
End Set
End Property
End Class
Public Enum EventLevel
[Information]
[Warning]
[Error]
[Critical]
[Fatal]
End Enum
And create a public variable just for this (and add an initial event to the AppEvents list)
Namespace My
Partial Friend Class MyApplication
'global variable here (using this for logging asynch call errors, then dumping this into a log file when all asynch calls are complete (due to file contention of log file)
Public AppEvents As New List(Of AppEvent)
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
'create first event and add it to the global variable declared above
AppEvents.Add(New AppEvent With {.EventTime = Now, .Description = "Program Started", .Level = EventLevel.Information, .Source = "QBI"})
End Sub
End Class
End Namespace
Next, in my logging class, I have some methods for logging, flushing/writing the event(s)
Public Class AppLogging
Public Shared Sub WriteEventToAppLog(evt As AppEvent)
LogDataToFile(FormatLineItem(evt.EventTime, evt.Level, evt.Description, evt.Source))
End Sub
Public Shared Sub WriteEventsToAppLog(AppEvents As List(Of AppEvent))
Dim sbEvents As New StringBuilder
If AppEvents.Count > 0 Then
For Each evt In AppEvents
sbEvents.AppendLine(FormatLineItem(evt.EventTime, evt.Level, evt.Description, evt.Source))
Next
LogDataToFile(sbEvents.ToString.TrimEnd(Environment.NewLine))
End If
End Sub
Private Shared Function FormatLineItem(eventTime As Date, eventLevel As EventLevel, eventDescr As String, eventSource As String) As String
Return String.Format("Logged On: {0} | Level: {1} | Details: {2} | Source: {3}", eventTime, System.Enum.GetName(GetType(EventLevel), eventLevel).Replace("[", "").Replace("]", ""), eventDescr, eventSource)
End Function
Private Shared Sub LogDataToFile(eventLogText As String, Optional ByVal LogFileName As String = "Error.log", Optional ByVal HeaderLine As String = "****** Application Log ******")
'log file operations
Dim LogPath As String = System.AppDomain.CurrentDomain.BaseDirectory()
If Not LogPath.EndsWith("\") Then LogPath &= "\"
LogPath &= LogFileName
Dim fm As FileMode
Try
If System.IO.File.Exists(LogPath) Then
fm = FileMode.Append
Else
fm = FileMode.Create
eventLogText = HeaderLine & Environment.NewLine & eventLogText
End If
Using fs As New FileStream(LogPath, fm, FileAccess.Write)
Using sw As New StreamWriter(fs)
sw.WriteLine(eventLogText)
End Using
End Using
My.Application.AppEvents.Clear() 'clears the global var
Catch ex As Exception
'handle this
End Try
End Sub
Public Shared Sub WriteEventToMemory(eventLevel As EventLevel, eventDescription As String, Optional eventSource As String = "")
Dim evt As New AppEvent
evt.Description = eventDescription
evt.Level = eventLevel
evt.EventTime = Now
evt.Source = eventSource
Try
My.Application.AppEvents.Add(evt)
Catch ex As Exception
Throw
End Try
End Sub
Public Shared Sub FlushEventsToLogFile()
WriteEventsToAppLog(My.Application.AppEvents)
End Sub
End Class
There's a few methods in here, but the method called in every exception handler is WriteEventToMemory (it merely adds an AppEvent to the AppEvents list).
An example test routine/worker process (to the local database) looks like:
#Region "local db test"
Private Sub TestLocalDBWorkerProcess_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles TestLocalDBWorkerProcess.DoWork
Me.TestLocalDBStatusMessage = TestLocalDB()
End Sub
Private Sub TestLocalDBWorkerProcess_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles TestLocalDBWorkerProcess.RunWorkerCompleted
Me.prgLocalDatabase.Style = ProgressBarStyle.Blocks
Me.prgLocalDatabase.Value = 100
If Me.ForcedCancelTestLocalDB Then
Me.lbStatus.Items.Add("Local DB Test Cancelled.")
Else
If TestLocalDBStatusMessage.Length > 0 Then
Me.lblLocalDatabaseStatus.Text = "Fail"
Me.lbStatus.Items.Add(TestLocalDBStatusMessage)
SendMessage(Me.prgLocalDatabase.Handle, 1040, 2, 0) 'changes color to red
Else
Me.lblLocalDatabaseStatus.Text = "OK"
Me.lbStatus.Items.Add("Connection to local database is good.")
Me.prgLocalDatabase.ForeColor = Color.Green
End If
End If
Me.ForcedCancelTestLocalDB = False
Me.TestLocalDBProcessing = False
ProcessesFinished()
End Sub
Private Sub StartTestLocalDB()
Me.prgLocalDatabase.Value = 0
Me.prgLocalDatabase.ForeColor = Color.FromKnownColor(KnownColor.Highlight)
Me.prgLocalDatabase.Style = ProgressBarStyle.Marquee
Me.TestLocalDBProcessing = True
Me.TestLocalDBStatusMessage = String.Empty
Me.lblLocalDatabaseStatus.Text = String.Empty
TestLocalDBWorkerProcess = New System.ComponentModel.BackgroundWorker
With TestLocalDBWorkerProcess
.WorkerReportsProgress = True
.WorkerSupportsCancellation = True
.RunWorkerAsync()
End With
End Sub
Private Function TestLocalDB() As String
Dim Statusmessage As String = String.Empty
Try
If Me.TestLocalDBWorkerProcess.CancellationPending Then
Exit Try
End If
If Not QBData.DB.TestConnection(My.Settings.DBConnStr3) Then
Throw New Exception("Unable to connect to local database!")
End If
Catch ex As Exception
Statusmessage = ex.Message
AppLogging.WriteEventToMemory(EventLevel.Fatal, ex.Message, "TestLocalDB")
End Try
Return Statusmessage
End Function
#End Region
The try-catch block simply catches the exception and writes it to memory (I just wrapped it in the WriteEventToMemory method, but it's just adding it to the AppEvents list: My.Application.AppEvents.Add(evt)
Everything appeared to be working peachy, until I noticed that the count for AppEvents was (1) after the Startup event, then it's count was (0) from any of the child processes, finally, the count was (1) when the list was dumped to the error log file (only the first event added was there). It is clearly acting like there are multiple versions of the AppEvents variable.
****** Application Log ******
Logged On: 10/7/2016 6:01:45 PM | Level: Information | Details: Program Started | Source: QBI
Only the first event shows up, the other events not (they are added, there's no null ref exceptions or any exceptions - like phantoms). Any event added to the global variable on the MAIN thread stays (and gets logged, ultimately). So this is clearly a multithreaded issue (never tried this before in a Windows app).
Any ideas on how to remedy?
As mentioned above, I had to pass the events back to the calling workerprocess, so, in the main form I put in:
Private AppEvent_TestLocalDB As New AppEvent
In the DoWork (for each process), I changed it to:
Private Sub TestLocalDBWorkerProcess_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles TestLocalDBWorkerProcess.DoWork
Me.TestLocalDBStatusMessage = TestLocalDB(AppEvent_TestLocalDB)
End Sub
The TestLocalDB sub now looks like:
Private Function TestLocalDB(ByRef aEvent As AppEvent) As String
Dim Statusmessage As String = String.Empty
Try
If Me.TestLocalDBWorkerProcess.CancellationPending Then
Exit Try
End If
If Not QBData.DB.TestConnection(My.Settings.DBConnStr3) Then
Throw New Exception("Unable to connect to local database!")
End If
Catch ex As Exception
Statusmessage = ex.Message
With aEvent
.Description = ex.Message
.Level = EventLevel.Fatal
.Source = "TestLocalDB"
End With
End Try
Return Statusmessage
End Function
Note there is no error logging, just the event variable (ByRef to pass it back, the equivalent to C# out).
When the worker process completes, I add the following:
With AppEvent_TestLocalDB
AppLogging.WriteEventToMemory(.Level, .Description, .Source)
End With
(the other worker processes work the same way)
When ALL the processes are complete, then I flush it to the log file.
AppLogging.FlushEventsToLogFile()
Now the custom event/error log entries look like so (with a freshly made file):
****** Application Log ******
Logged On: 10/7/2016 10:14:36 PM | Level: Information | Details: Program Started | Source: QBI
Logged On: 10/7/2016 10:14:53 PM | Level: Fatal | Details: Unable to connect to local database! | Source: TestLocalDB
That was it - just pass the variable back to the caller

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

VB.Net Passing values to another form

I would like to know how to pass a value from form1 to another form's public sub.
The problem is that it says "it is not accesible in this context because it is 'Private'."
I've tried changing Form 1 Private Sub to Public Sub but the same error remains. How should i make it work?
Public Class Form1
Dim test(), text1 As String
Const asd = "abcabc"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
text1 = Space(LOF(1))
test = Split(text1, asd)
HOST = test(1)
End Sub
And i want to pass HOST = test(1) value to another form
Public Class Form2
Public Sub Check()
'get the value to here
End Sub
You could pass it as a parameter:
Public Sub Check(valueToCheck as String)
'get the value to here
End Sub
Or create a property on form2 to receive it:
private _HostOrSomething As String = ""
Friend Property HostOrSomething As String
Get
Return _HostOrSomething
End Get
Set(ByVal value As String)
_HostOrSomething = value
End Set
In which case, Sub Check could use _HostOrSomething since it is local var. To use these:
HOST = Test(1)
frm2.Check(HOST)
or
HOST = Test(1)
frm2.HostOrSomething = HOST
frm2.Check
You can use global variables to pass data from one from to another
Dim A As New Integer= 10
Here how you declare the global The class can be define anywhere in the application.
Public Class GlobalVariables
Public Shared INTver As Integer
End Class
And how you use global variable to store the answer is here
GlobalVariables.INTver= A
put this lines in your "privet sub" and you can access the variable to any of your form that is in your WINDOWS application.