call objects from other forms!

sepehr

Member
Joined
Oct 7, 2005
Messages
5
Location
Karaj
Programming Experience
Beginner
i have 2 forms , i have created a button in the forst form tha brings up the second form when it is clicked and the second form has a button.
now there is the problem ,i have a textbox on the first form and i want to when the button on the second form is clicked the value of the textbox in the first button is changed to "Neo" , what should i do?:confused:
 
No need to cast from type Form1 to type Form1 :). (The answer is no).
It's probably a better idea to use Form1 as the parameter type in this case (as shown in the last post) since you are expecting to work with the Form1 class and its methods/properties. As originally written in post 7, if you were to pass a form that was not of type Form1 then the DirectCast would fail.
 
jain_mj said:
suppose we are writing
Public Sub New(ByVal f As Form)
then what can we do to find the type of form we are getting as the argument?
You would normally have some idea of what it would be at design time, either a specific type or a number of types that it could be. If you know exactly what type it will be then you should declare the argument as that type. If it can be a number of types then you have choices. You could either use If statements to check the type:
VB.NET:
If TypeOf f Is Form1 Then
    DirectCast(f, Form1).SomeMethodOfForm1()
ElseIf TypeOf f Is Form2 Then
    DirectCast(f, Form2).SomeMethodOfForm2()
ElseIf TypeOf f Is Form3 Then
    DirectCast(f, Form3).SomeMethodOfForm3()
End If
or you could overload the constructor so the type is selected automatically:
VB.NET:
Public Sub New(ByVal f As Form1)
     f.SomeMethodOfForm1()
End Sub

Public Sub New(ByVal f As Form2)
     f.SomeMethodOfForm2()
End Sub

Public Sub New(ByVal f As Form3)
     f.SomeMethodOfForm3()
End Sub
Another option would be to use Reflection but that is getting too complex for the majority of situations. Note that this situation already exists for MDI child forms. The MdiParent property is of type Form, so to use its members other than those inherited from the Form class you need to have some idea about what type it is and cast it accordingly.
 
Did you try it by adding an event handler in form1 that manages the button in form2?. It'd be pretty simply to get it done:

Dim form2 As New form2()

addHandler form2.MyButton, AddressOf WriteText

form2.Show()

This is WriteText method:

Private Sub WriteText(...)

MyTextBox.Text = "Neo"

End Sub

WriteText method must have the same type of params that normals event handlers has, it means that it must have an Object and EventArgs as params.

Regards!.
 
Back
Top