How to call new class with global scope from function - vb.net

Salvete! I want to create a new instance of a class when I click on a button, but I need to interact with members of that class using other controls on the form, so I need the class to have a global scope. I know I could call the new class in formload, but the class creates certain variables that need to be current. If it is done on formload, the variables wouldn't be current, because if the class is created at formload, it would have different info at that time. Surely, there must be a way to create an instance of the myClass from within a sub that is accessible from other subs of the same class.
Something like this:
click on myForm.button1 to dim myclassInstance as new myClass
then, click on myForm.button2, to make mylabel.text = myClassiInstance.myvariable

First, you may be having problems because MyClass is a reserved keyword, so if you are trying to create a class with this name, you will need to choose a different class name.
Having said that, I believe that what you want is something similar to the following, where we store the instance of the class as a private member of the form. This instance will only "live" as long as the form exists, so if it needs to be share among forms, then you will need to move the instance to a different location (a global variable or a shared member).
Public Class Form1
Private m_CurrentInstance As ThisIsMyClass
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
m_CurrentInstance = New ThisIsMyClass
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
If m_CurrentInstance IsNot Nothing Then
myLabel.Text = m_CurrentInstance.MyVariable
End If
End Sub
End Class

It's difficult to understand what you are asking for but it seems like you just want to check out the Shared keyword. Basically Shared means single instance.
So whatever you apply it to will be created only once and be tied to the type of the class not an instance of it.
Private Shared sharedInt As Integer
Private Shared sharedPropValue As String
How to create and use shared members by using Visual Basic .NET

Related

How do I pass an object to a default form instance

I understand its possible to open the "default instance" of a form in vb.net by calling NameOfTheForm.show()
How do I pass an object to the default form instance so i can work on the object and use it to populate the forms Text boxes?
I've tried to add a parameter to the frmNames New method but I'm not sure how then to open the form. The old style instantiate an object works:
Dim DetailsForm As New frmOrder(oOrder)
DetailsForm.Show()
But I'm used to using the :
frmOrder.show
syntax.
Should I use the top method or should I use the bottom method and have a public property on the form to accept the Object?
Have a missed a better method of doing this?
Thanks
Your calling method should use your first option
'Careful about declaring this in a sub, because when that sub ends, the form might get closed.
'It might be best to declare this as an instance var (aka form-level var)
Private DetailsForm As frmOrder
'this could go in an event handler, or anywhere
DetailsForm = New frmOrder(oOrder)
DetailsForm.Show()
You will need to add a constructor to your DetailsForm:
Private _oOrder as OrderType
Public Sub New(oOrder As OrderType)
'Best to save it to a private instance var and process it during Form_Load
_oOrder = oOrder
End Sub
Then when your Form_Load() runs, it can use your private instance var to fill your TextBoxes, like you want.
A second, but less eloquent approach would be to add a public property to the form and after you call .Show(), you can assign a value DetailsForm.OrderObject = oOrder, and then process the object that was passed-in.
The constructor approach is better because it can be "compiler checked"
If you really feel you must use default instance.
In Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.myObject = New Coffee("Breakfast Blend", 7)
Form2.Show()
End Sub
In Form2
Public myObject As Coffee
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = myObject.Name
TextBox2.Text = myObject.ID.ToString
End Sub

Handles an Event from Control in another class

I want to fire an event in another class.
And my problem is I don't know how to make it.
I'm trying to use Inherits statement to my Form and add my class name to it, and it works as I hope:
Public Class Frm_Main_Copy
Inherits ToolStripMenuApp
'I have a ToolStripMenu that has declared before on my class and it sounds like this:
'Public Shared WithEvents Cat000x86_64App As ToolStripMenuItem
...
Private Sub IsClicked(ByVal sender As Object, ByVal e As EventArgs) Handles Cat000x86_64App.Click
End Sub
End Class
but the designer form messed up(returns a fatal error) and I should delete the Inherits statement, and the others.
Tried to act as form designer script(Trying to put this code to my class):
Friend WithEvents BlahBlah As RadioButton 'For example
It didn't worked,
Declaring a variable for my class and It didn't worked too
Searched on the Internet and it seems likely more complicated than I thought...
Anyone can help? Any help is appreciated.
A form is not a form unless it inherits, either directly or indirectly, the Form class. You cannot inherit any type that is not itself a form and expect your type to be a form. With that code, if ToolStripMenuApp is not a form then Frm_Main_Copy is not a form either, hence no form designer.
If what you're actually saying is that you have an instance of that ToolStripMenuApp that contains a TooStripMenuItem whose Click event you want to handle in Frm_Main_Copy then the first step is to not declare Cat000x86_64App as Shared. Frm_Main_Copy needs to declare a method capable of handling that event:
Private Sub IsClicked(ByVal sender As Object, ByVal e As EventArgs)
'...
End Sub
Note that there is no Handles clause because there's no WithEvents variable in that class whose event you are handling.
Next, Frm_Main_Copy must have access to the appropriate instance of ToolStripMenuApp. It's impossible for us to say how best to do that based on the information provided but it might be as simple as this:
Dim tsma As New ToolStripMenuApp
You then register your method as a handler for the appropriate event:
AddHandler tsma.Cat000x86_64App.Click, AddressOf IsClicked
If you use AddHandler, make sure to use RemoveHandler when you're done with either object. I suggest that you do some reading based on this information.

Embed database in vb.net app

I'm building a small VB.net app. I want to add a little database (about 5 columns, 20 records). I want to keep everything in a single exe. I think it's a bit overkill to add a 'full' database, so I'm looking for an alternative.
I could create a CSV file, and add it as a resource. Is this a good idea, or are there any other better alternatives?
Another option for such a small amount of data is to store it in ApplicationSettings. Your question implies you are using WinForms, so you can make use of the built-in features with just a small amount of work to store your own custom class.
Create a class to represent your data.
Wrap that class in a property of another class that inherits from ApplicationSettingsBase as a List(Of )
Manipulate this custom setting as needed and call Save() as needed.
Here is an example that binds to a DataGrid:
The class that represents your data:
Public Class Fruit
Public Property FruitName As String
Public Property FruitColor As String
Public Property FruitGrowsOn As String
End Class
The class that turns Fruit into a collection stored in application settings. Notice it inherits ApplicationSettingsBase. Also notice the attributes on the Fruits property that identify this as a user setting as opposed to an application setting (which cannot be modified by the user). The DefaultSettingAttribute makes sure the collection is instantiated so you don't get null reference exception until after the first time you add an item:
Imports System.Configuration
Public NotInheritable Class FruitCollection
Inherits ApplicationSettingsBase
<UserScopedSettingAttribute()>
<DefaultSettingValue("")>
Public Property Fruits() As List(Of Fruit)
Get
Fruits = Me("Fruits")
End Get
Set(ByVal value As List(Of Fruit))
Me("Fruits") = value
End Set
End Property
End Class
The Form definition. Retrieves the instance of your custom setting (FruitUserSettings), creates a binding source for a DataGridView, and provides a Save button to persist the changes made in the grid to Settings. Next time the user opens the form the changes will still be there provided they clicked the Save button:
Public Class Form1
Dim FruitUserSettings As FruitCollection
Dim GridBindingSrc As BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FruitUserSettings = New FruitCollection()
GridBindingSrc = New BindingSource(FruitUserSettings, "Fruits")
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = GridBindingSrc
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FruitUserSettings.Save()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
GridBindingSrc.Dispose()
End Sub
End Class
Note, you don't need a binding source or grid, these were just for demonstration. You can manipulate FruitUserSettings.Fruits like any other list in any way you want. As long as Save() is called on the settings you will retain the data.
You can download/clone the working sample here: https://github.com/crowcoder/CustomSetting
i would use XML file as little database, you can query it easily with linq (Language-Integrated Query). also there are built in library's that can help you handle you records and query's. of course that you can use access, excel (you can query excel with SQL) csv or txt file . also you can create a local data base file in visual studio

How do you interact with a form when in a BackgroundWorker class 'completed' function?

I have a BackgroundWorker that is used to carry a time consuming process while a form is shown. The form and the BackgroundWorker are in separate classes, and when the BackgroundWorker has finished what it has to do, I need to carry out some basic actions on the form.
However, the below does not work and produces the warning Reference to non-shared member requires an object reference.
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
mainForm.btnCancel.Enabled = False
mainForm.btnFinish.Enabled = True
End Sub
I researched the warning and it suggested that I had to ensure the object mainForm was declared, which for this scenario seems odd from the get go. Regardless, I changed my code to this, and the warning disappeared, but as suspected, it doesn't work. It seems that a new instance of the form would be referenced, which is not what I require.
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
Dim objForm As New mainForm
objForm.btnCancel.Enabled = False
objForm.btnFinish.Enabled = True
End Sub
Can someone please tell me how I can interact with a form from a BackgroundWorker? Thanks.
The problem is not that you need to declare a new mainForm object. The problem is that you need a reference to the right mainForm object. Since it is possible to create any number of mainForm objects, you need a reference to the particular mainForm object that you want to modify. Remember, mainForm is the class (a type of object). It is not, itself, an object.
The simplest way fix this would be to give a reference to the mainForm object to the class that is performing the work, like this:
Public Class MyBusiness
Public Property TheMainForm As mainForm
' ...
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
TheMainForm.btnCancel.Enabled = False
TheMainForm.btnFinish.Enabled = True
End Sub
End Class
Then, before starting the work, you need to make sure you set the TheMainForm property. For instance, something like this:
Dim business As New MyBusiness
business.TheMainForm = Me
business.DoWork()

VS 2010 Ultimate VB.NET Project form won't compile/show up

When press F5 to compile a project, there are no errors or warnings but the form won't show up. What's up?
Every time that you try to run your code, it starts by creating an instance of frmMain, your default form and the one that is shown at application startup.
When this form is created, it automatically instantiates an instance of Form3 because you instantiate a variable of that type called modifyForm at the top of this form's code file:
Dim modifyForm As New Form3 'modify student
The problem is that, when the runtime goes to instantiate an object of type Form3, it gets called right back to where it was because of this statement at the top of the Form3 code file:
Dim frmMain As New frmMain
Rinse, lather, and repeat. Your code turns into an infinite loop, trying to instantiate an instance of frmMain, which tries to instantiate an instance of Form3, which tries to instantiate an instance of frmMain, ad nauseum. Eventually, this will overflow your available memory and cause a StackOverflowException.
It's important to note that all of this happens before the default instance of frmMain is even shown, because these variables are declared outside of any methods in your code. Because the computer never can escape this infinite loop, it never gets a chance to move on and actually display your form.
And the moment you've all been reading so patiently for:
Fix it by removing the declaration of frmMain at the top of the Form3 code file. I don't know what that's there for, anyway.
EDIT: Hopefully, I can clear up a little confusion regarding passing values between forms. Upon further study of your code, my instincts tell me that the best solution for you is to overload the constructor for Form3 to accept the calling form (the existing instance of frmMain) as an argument. This will allow you to access all of the public members of frmMain from within your Form3 class.
Here's a rough sketch of how you might do this in your code:
Public Class frmMain
''#The private data field that stores the shared data
Private _mySharedData As String = "This is the data I want to share across forms."
''#A public property to expose your shared data
''#that can be accessed by your Form3 object
Public Property MySharedData As String
Get
Return _mySharedData
End Get
Set(ByVal value As String)
_mySharedData = value
End Set
End Property
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
''#Do all of your other stuff here...
''#Create a new instance of Form3, specifying this form as its caller
Dim otherForm As New Form3(Me)
''#Show the new instance of Form3
otherForm.Show()
End Sub
End Class
Public Class Form3
''#The private field that holds the reference to the main form
''#that you want to be able to access data from
Private myMainForm As frmMain
Public Sub New(ByVal callingForm As frmMain)
InitializeComponent()
''#Save the reference to the calling form so you can use it later
myMainForm = callingForm
End Sub
Private Sub Form3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
''#Access anything that you need from the main form
MessageBox.Show(myMainForm.MySharedData)
End Sub
End Class
As you can see, frmMain exposes a public property (backed by a correspondingly-named private variable) called MySharedData. This can be absolutely anything you want, and you can have as many of these as you want.
Also notice that how the constructor (the New method) for Form3 accepts an instance of frmMain as an argument. Whenever you create a new Form3 object from frmMain, you just specify Me, which indicates that you want to pass the current instance of frmMain. In the constructor method, Form3 stores that reference to its calling form away, and you can use this reference any time you like in Form3's code to access the public properties exposed by frmMain.
In VS2010 menu, go to Build -> Configuration Manager, does your project have the checkbox in the "Build" column enabled?
If it's project upgraded from an older Visual Studio version it may be that it is not targeting .NET Framework 4.0. In that case you should change it as explained here.
To analyze the problem press F8 (or F10, depends on your default keyboard settings) to step into the code instead of running the app. This should take you to the main method where the main form would be initialized.