Friday, July 3, 2009

Windows Form to retrieve information from Calling Form

We can pass information from calling form to a new form. But what if the called form wants to refer the properties of the calling form?

How to allow the called form to access the properties or controls of calling form(Parent Form).?

The Form can refer that calling Form(Parent Form) by using the "Owner" Property


The following VB.NET code explains that...

Form1

Drag Button Control to a form (Form1) and name it as Button1.

Drag text box control to a form (Form1) and name it as TextBox1

Form2
Drag Button Control to a form (Form2) and name it as Button2.



Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim f As New Form2

f.ShowDialog(Me)


End Sub
End Class

Public Class Form2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show("Parent form text: " + CType(Me.Owner, Form1).Text)
Dim btntext As String
'Access the Form1's TextBox text
btntext = CType(Me.Owner, Form1).TextBox1.Text
MsgBox(btntext)
End Sub
End Class



In this example i simply refer to the Title of the parent form and text box's text but we could other properties as well.

No comments:

Post a Comment