Passing value from one form to another using events in vb.net - vb.net

I'm trying to pass a value from one form, let's call it Form1 to another form, Form2. When i double click a row in a listview that is in Form2, the value should be passed to a combobox in Form1.
I could get one of my other forms to do this using an event called PropertyChanged, but I can't seem to get it to work on other forms. I don't know if it is the fact that you can only have 1 event in the entire project and not have another with the same name. I'm missing something, but i just don't know where.
This is the code i used in Form2:
Public Event PropertyChanged As Action(Of Object)
Private Sub ListView2_DoubleClick(sender As Object, e as EventArgs) Handles ListView2.DoubleClick
RaiseEvent PropertyChanged(ListView1.SelectedItems(0).SubItems(0).Text)
End Sub
And this is the code I used in Form1:
Dim WithEvents f2 As Form2
Private Sub PropertyChanged(obj As Object) Handles f2.PropertyChanged
cmb_form1.Text = obj
End Sub

There are several ways to implement this. This one is quick and dirty.
It consists of writing up a property in Form2 which is public. When the user makes a choice, it goes in the property. Then Form1 reads the property before it disposes Form2.
Here's a little code snippet to better illustrate what I mean:
Public Class Form1
' This form has a button which opens a Form2 instance
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim form2 As New Form2 ' instantiate Form2
form2.ShowDialog() ' the user chooses a value
MessageBox.Show(form2.Result) ' get it before it's out of scope!
End Sub
End Class
Public Class Form2
Public Property Result As String ' the value is stored in there, it can be any type
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Result = "Clicked!" ' store the value you want to share between forms
Me.Close()
End Sub
End Class
Have fun!

Related

Add combobox items from another usercontrol form using textbox

I have a usercontrol form named "ucSETTINGS", where there is a textbox and once the button was clicked, the text inside the textbox will be added to the combobox from another usercontrol form name "ucITEMS"
I tried this code but it's not working
(cboCategory is the name of the combobox from ucITEMS, txtNAME is the textbox from ucSETTINGS)
Private Sub btnSAVE_Click(sender As Object, e As EventArgs) Handles btnSAVE.Click
Dim category As New ucITEMS()
category.cboCATEGORY.Items.Add(txtNAME.Text)
End Sub
Can someone help me?
In this sort of situation, the user controls don't know about each other by default and it should stay that way. The source UC just exposes an interface and lets whomever is watching use that as it sees fit. That means raising an event when something happens and exposing required data via properties, e.g.
Public Class SourceControl
Public ReadOnly Property TextBox1Text As String
Get
Return TextBox1.Text
End Get
End Property
Public Event Button1Click As EventHandler
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OnButton1Click(EventArgs.Empty)
End Sub
Protected Overridable Sub OnButton1Click(e As EventArgs)
RaiseEvent Button1Click(Me, e)
End Sub
End Class
The Text of the TextBox is exposed via a property and, when the user clicks the Button, the UC raises an event.
The destination UC provides an interface for new items to be provided but it adds them to its own ComboBox, e.g.
Public Class DestinationControl
Public Sub AddItemToComboBox1(item As Object)
ComboBox1.Items.Add(item)
End Sub
End Class
The form then plays go-between, handling the event, getting the property and calling the method:
Private Sub SourceControl1_Button1Click(sender As Object, e As EventArgs) Handles SourceControl1.Button1Click
DestinationControl1.AddItemToComboBox1(SourceControl1.TextBox1Text)
End Sub
Obviously you would use something more specific and appropriate than my generic naming.

How to keep the data of a form after hiding it

The user enters data in Form1 for example his name and phone number, he clicks on the "next" button that opens Form2 and Hide Form1, if he clicks on the "back" button I want the program to show Form1 with the data he entered before
The code for the "Next" Button in Form1:
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
Dim MyForm As New Form2
MyForm.Show()
Me.Hide()
End Sub
What should I do in order to keep the data the user entered if he comes back to Form1?
The code for the "Previous" button in Form2:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form1.Show()
Me.Close()
End Sub
One approach you could use is to only the use the DEFAULT INSTANCES of your Forms. These are accessed by using only the name of the Form, WITHOUT ever using the "New" keyword.
You're doing exactly that in Form2 when you show Form1 with:
Form1.Show()
This works because Form1 is your startup object and VB.Net used the default instance to start the application.
You could do the same thing in Form1, to show Form2:
' ... code in Form1 ...
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
Form2.Show() ' show the default instance of Form2 (do NOT use the "new" keyword)
Me.Hide()
End Sub
Just make sure in all places you Hide() the current form instead of closing it.
You can access the properties/fields of the default instances using the same syntax to show them, using only their name. For example, here is a made up value being accessed on Form2:
Dim userName As String = Form2.txtAddress1.Text
This assumes that Form2 was previously displayed and populated by the user. You could access the Forms from anywhere in the code using this type of syntax.
If you want to implement your own "default instance" mechanism, you could use Shared members in a class:
Public Class WizardForms
Public Shared F1 As New Form1
Public Shared F2 As New Form2
Public Shared F3 As New Form3
End Class
Then you could use code like this to display one:
WizardForms.F2.Show()
This would work as long as you are only HIDING the forms. If you allow the user to close the Forms (or close them via code), then you'd need extra code to make sure they get recreated as needed.

VB.NET User control Referencing Form

I have a form (frmwizard) which I am using to create a wizard like interface. The form contains a usercontrol and a button (for testing). There is also a function on the form called "NextPage"
The form loads a usercontrol (ucpage1) on load and the usercontrol has a button on it that when clicked attempts to call a function on the main form as per below:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frmWizard.Nextpage(me.name)
End Sub
Within my function called "NextPage" have the following for testing.
Public Sub NextPage(ByVal CurrentPage As String)
MessageBox.Show(UserControl1.Controls.Count)
End Sub
When I call the function from the form itself (via the button) I get the result of 1, when i call the function via the User Control, I get the result as 0
I'm sure there is something simple I need to do, but i'm unsure what i've overlooked.
I am trying to make the button on the user-control Save the data within the control and then to browse to the next wizard page. Hopefully this is enough information
Codependance is a bad idea, as it locks the two types together for the future. If your user control really needs to invoke the form, you should instead have it raise an event and handle the event in your form.
Public Class MyUserControl
Public Event OnNextPage(ByVal sender As Object, ByVal e As EventArgs)
Private Sub btnNextPage_Click(sender As Object, e As EventArgs) Handles btnNextPage.Click
RaiseEvent OnNextPage(Me, New EventArgs)
End Sub
End Class
Public Class Form1
Private Sub MyUserControl_OnNextPage(sender As Object, e As EventArgs) Handles MyUserControl1.OnNextPage ' , MyUserControl2.OnNextPage, etc...
MessageBox.Show(DirectCast(sender, MyUserControl).Controls.Count)
End Sub
End Class

VB.NET Absolutely strange form load behaviour

I am experiencing a strange behaviour when using RightToLayout layout:
My form automatically closes.
I have created a simple project to reproduce the problem:
Create a new VB.NET project in VS2012 and add forms "Form1" and "Form2" to it.
Set "Form1" to be the start form.
Then add the following code to "Form1":
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Hide()
Dim f As New Form2
f.ShowDialog()
MessageBox.Show("After dialog closed.")
modControls.setFormRTL(Me) 'This line causes the Form2 to automatically close. Why??? This line should only be processed AFTER the dialog has been shown and closed
End Sub
End Class
Add the following code to "Form2":
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
modControls.setFormRTL(Me)
End Sub
End Class
Add a module with the name "modControls" to the project.
Add the following code to it:
Module modControls
Public Sub setFormRTL(ByVal uForm As Form)
uForm.RightToLeft = RightToLeft.Yes
End Sub
End Module
Without the setFormRTL, my project works perfectly fine, but with it, "Form2" automatically closes down. You can see this because the messagebox is shown.
When I remove the line
modControls.setFormRTL(Me)
from Form1 load, it works fine again.
Yes, I really mean from "Form1", not from "Form2"!!!
Now this is really strange because it should not matter at all because this line is not processed before the dialog is closed.
I hope somebody understands what I mean.
Can anybody shed some light on what might be happening here?
Yes, you'll get unexpected behavior if you set the RightToLeft property anywhere other than a control's constructor (in VB.NET parlance, that's the New method).
In fact, the constructor is where you should set all of the properties of a form or control object. If you come from VB 6, it might seem logical to do it in the Load event handler, but that's not idiomatic .NET and, as you've discovered, can cause problems when initializing certain properties.
The technical reason for this is that certain properties (like RightToLeft) can actually only be set on the native window (which is how the Form objects used in the .NET world are implemented behind the scenes) at the time that it is created. When you attempt to change the property, the framework code actually has to destroy and then re-create the native window with the new property values.
Change the code to look like this instead:
Public Class Form1
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
modControls.SetFormRtl(Me)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Hide()
Dim f As New Form2
f.ShowDialog()
MessageBox.Show("After dialog closed.")
End Sub
End Class
Public Class Form2
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
modControls.SetFormRtl(Me)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Speaking of non-idiomatic .NET code:
Methods should all be Pascal cased by convention. That means your setFormRTL method should be named SetFormRtl.
A helper function that sets the properties of an object just seems wrong to me. If anything, that's just bad OO design. If you want this method to be available for all of your Form objects, derive a custom form class and add this method (or even do the desired initialization in the constructor). Either way, all forms that you derive from this custom form object will inherit the functionality. Example:
Public Class MyCustomForm : Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
Me.SetRtl()
End Sub
Public Sub SetRtl()
Me.RightToLeft = RightToLeft.Yes
End Sub
End Class
Public Class Form1 : Inherits MyCustomForm
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Hide()
Dim f As New Form2
f.ShowDialog()
MessageBox.Show("After dialog closed.")
End Sub
End Class
Public Class Form2 : Inherits MyCustomForm
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
can you try this? all i am doing here is setting the RTL before the form is displayed.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Hide()
Dim f As New Form2
modControls.setFormRTL(f)
f.ShowDialog()
MessageBox.Show("After dialog closed.")
modControls.setFormRTL(Me)
End Sub
End Class
and remove code form load event of form 2

Using Variables Across Forms - VB

I've got a fairly simple question (I think) on passing variables between forms using Visual Basic.
I've got a program with 2 forms (Form1 and Form2). Form1 has 3 radio buttons, which the user has to select one of and then loads Form2.
Now I've made it so that if radiobutton1 is picked, the Public Variable "radio_select" will equal "radiobutton1", if radiobutton2 is picked, "radio_select" will equal "radiobutton2".
But whenever I try call "radio_select" in my second form, it comes up blank. Why could this be? And how can I fix it.
I've tried using if form1.radiobutton1.checked = true but I keep getting the first radiobutton, regardless of the radio button I've selected.
I think the form is being unloaded, or there is an issue somewhere there, as it appears none of the variables get passed to the second form, once it has been initialized. Also note, the first form is hidden Me.Hide() when the second form is called.
Have you considered a slight re-design whereby you create a property on Form2 called RadioSelect and then set this from Form1 before showing Form2:
Class Form2
Public Property RadioSelect As String
...
End Class
...
Dim f2 as new Form2()
f2.RadioSelect = "radiobutton2"
f2.Show() ' Or f2.ShowDialog()
This gets you away from an unnecessary public variable and should also ensure Form2 can see what it needs from Form1, or whoever calls it.
Edit:
The following works for me:
Public Class Form1
Public Test As String
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Test = "I'm Here"
Me.Hide()
Form2.ShowDialog()
End Sub
End Class
Public Class Form2
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Text = Form1.Test
End Sub
End Class