Wednesday, July 16, 2008

How to Pass Data Across Forms

In this post we will discuss how can we share different variables among Forms.

Level: Beginner

Knowledge Required:
Win Forms

Description:
While creating a Windows Forms Application, we usually face a requirement when we need to pass one or more variables from one Form to another. For example, we have created a Dialog Box which takes Date Range,

When we display this dialog box, we want that a default date range should be given, also this dialog box should return the new Date Range that is selected.

To pass the data to Form we can directly use Form's Control as,

In Form1.Button1.Click Event Handler:

DateRangeDialog.DateTimePicker1.Value = Now

As you can see the above code, I have used the DateRangeDialog's DateTimePicker control in Form1's Button Click event Handler, but it is better to create Public Properties on Form and use them. Also we can utilize the Constructor (New Method).

Public Class dlgDateRange
Private _DateStart As Date
Private _DateEnd As Date

'Public properties that will be used to get the selected dates
Public ReadOnly Property DateStart() As Date
Get
Return Me
._DateStart
End Get
End Property

Public ReadOnly Property
DateEnd() As Date
Get
Return Me.
_DateEnd
End Get
End Property

' default constructor
Public Sub New
()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me._DateStart = Now
Me._DateEnd = Now
End Sub

' if dates are supplied on initializing
Public Sub New
(ByVal DateStart As Date, ByVal DateEnd As Date)
Me.New()
' Add any initialization after the InitializeComponent() call.
Me._DateStart = DateStart
Me._DateEnd = DateEnd
End Sub

' OK button is clicked
Private Sub
OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
' set the selected values and close dialog
Me._DateStart = Me.DateTimePicker1.Value
Me._DateEnd = Me.DateTimePicker2.Value
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub

' cancel button is clicked
Private Sub
Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub

' on form load event we will set the dates which were supplied on initializing
Private Sub
dlgDateRange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.DateTimePicker1.Value = Me._DateStart
Me.DateTimePicker2.Value = Me._DateEnd
End Sub
End Class

Usage:
Dim dlgNew As dlgDateRange
dlgNew = New dlgDateRange(New Date(2008, 1, 1), New Date(2008, 6, 30))
If dlgNew.ShowDialog() = Windows.Forms.DialogResult.OK Then
Debug.Print("Date Start: " & dlgNew.DateStart)
Debug.Print("Date End: " & dlgNew.DateEnd)
End If

No comments: