I have pretty much the same problem as described in this, but using VB.NET. There is a Form1 which is opened automatically as start window, so I cannot find the instance to use for accessing it. There is a Form2 opened from within Form1. I try to pass the instance of Form1 using keyword "Me":
Private Sub Button1_click(...) Handles Button1.Click
Dim childform as new Form2(Me)
childform.show()
End Sub
In Form2 I have:
Public Sub New(parentform As System.Windows.Forms.Form)
InitializeComponents()
MessageBox.Show(parentform.Button1.Text)
End Sub
Upon compiling I get the error: "Button1 is not a member of Form". So how to pass the Form1 instance correctly to Form2?
Also I want to change some properties of the Button1 of Form1 from Form2. Button1 is declared in a Private Sub, will I nevertheless be able to access it from Form2 if I pass the instance correctly? If not, can I declaring a sub in Form1, e.g.
Public Shared Sub ChangeText(newtext As Sting)
Me.Button1.Text=newtext
End Sub
that will do the job?
CodePudding user response:
I'm not 100% sure about what you are trying to achieve, but, you can pass data between forms. So for example you can do something like:
Public Class Form1
Private Sub Button1_click(...) Handles Button1.Click
Dim newForm2 as New Form2()
newForm2.stringText = ""
If newForm2.ShowDialog() = DialogResult.OK Then
Button1.Text = newForm2.stringText
End If
End Sub
End Class
And in Form2 you have
Public Class Form2
Dim stringText as string
Private Sub changeStringText()
'your method to change your data
Me.DialogResult = DialogResult.OK 'this will close form2
End Sub
End Class
I hope this is what you need, if not let me know
CodePudding user response:
Thanks for your answer and comment. So I declared the wrong class for the parentform, means in Form2 it needs to be "parentform as Form1":
Public Sub New(parentform As Form1)
InitializeComponents()
MessageBox.Show(parentform.Button1.Text)
End Sub
and yes, I need to skip the "shared" in the ChangeText:
Public Sub ChangeText(newtext As Sting)
Me.Button1.Text=newtext
End Sub
This way it worked for me.