StewieL
StewieL

Reputation: 7

Passing value from one form to another using events in 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

Upvotes: 0

Views: 665

Answers (1)

laancelot
laancelot

Reputation: 3207

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!

Upvotes: 1

Related Questions