ARTICLE

Passing Data Between Forms

Posted by Thiagarajan Alagarsamy Articles | Windows Forms VB.NET December 27, 2006
There are so many methods to pass data between forms in windows application. In this article let me take four important and easiest ways of accomplishing this.
Reader Level:

Introduction

 

Some of you would have faced a scenario where you wanted to pass data from one form to another in WinForms. Honestly, I too had a similar problem (that's why I am writing this article!).

 

There are so many methods (How many? I don't know) to pass data between forms in windows application. In this article let me take four important (easiest) ways of accomplishing this.

  1. Using constructor
  2. Using objects
  3. Using properties
  4. Using delegates

     

 

 

 

 

 

 

 

 

 

 

 

 

  

Passing Data Between Forms

    Let us see all the above methods in detail in the following sections.

     

    For a data to be passed between forms using any of the above methods, we need two forms and some controls. Let us start by following the below steps.

     

    Step 1: Create new project and select windows application. This will create a default form as "Form1". We can use this form for sending data.

     

    Step 2: Add a textbox and a button to the form.

     

    Step 3: Add another windows form for receiving the data and to display it. Right click the project and select Add->Add Windows Form. Enter a name or use the default name "Form2.vb" and click ok button.

     

    Step 4: Add a label to the second form to display the text from form1

     

    The Constructor Approach

     

    This could be the easiest method of all. A method is invoked whenever you instantiate an object. This method is called a constructor. Code a constructor for form2 class with one string parameter. In the constructor assign the text to the label's text property. Instantiate form2 class in form1's button click event handler using the constructor with one string parameter and pass the textbox's text to the constructor.

     

    Follow the below steps.

     

    Step 1: Code a constructor for form2 class as below 

     

    Public Sub New(ByVal strTextBox As String)

        InitializeComponent()

        label1.Text = strTextBox

    End Sub

     

    Step 2: Instantiate form2 class in form1's button click event handler as below

     

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 

        btnSend.Click

        Dim frm As Form2 = New Form2(textBox1.Text)

        frm.Show()

    End Sub

     

    The Object Approach

     

    Objects are reference types, and are created on the heap, using the keyword new. Here we are going to pass data using objects. The approach is simple; in form2 we are going to instantiate form1 class.

     

    Then instantiate form2 in the button click event handler of form1. After this we are going to pass form1 object to the form2 using form2's form1 object. The last step is to invoke the form2 window by calling the form2's show method.

     

    Follow the below steps:

     

    Step 1: Change the access modifier for textbox in form1 to public 

     

    Public Class Form1

        Inherits System.Windows.Forms.Form

        Friend WithEvents textBox1 As System.Windows.Forms.TextBox

    End Class       

     

    Step 2: In the button click event-handler add the following code.  

     

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 

        btnSend.Click

        Dim frm As Form2 = New Form2

        frm.frm1 = Me

        frm.Show()

    End Sub

     

    Step 3:  In form2.cs, instantiate form1 class 

     

    Public Class Form2

        Inherits System.Windows.Forms.Form

        Public frm1 As Form1

    End Class

     

    Step 4: In Form2's Load method type cast the object (frm1) of form1 to Form1 and access form1's textbox and assign its text to label's text.  

     

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

        MyBase.Load

        label1.Text = CType(frm1, Form1).textBox1.Text

    End Sub

     

    The Properties Approach

     

    Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. In this method we are going to add one property to each form. In form1 we are going to use one property for retrieving value from the textbox and in form2, one property to set the label's text property. Then, in form1's button click event handler we are going to instantiate form2 and use the form2's property to set the label's text.

     

    Follow the below steps:

     

    Step 1: Add a property in form1 to retrieve value from textbox. 

     

    Private ReadOnly Property _textBox1() As String

        Get

            Return textBox1.Text

        End Get

    End Property

     

    Step 2: Add a property in form2 to set the labels' text  

     

    Friend WriteOnly Property _textBox() As String

        Set(ByVal Value As String)

            label1.Text = Value

        End Set

    End Property

     

    Step 3: In form1's button click event handler add the following code.  

     

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 

        btnSend.Click

        Dim frm As Form2 = New Form2

        frm._textBox = _textBox1

        frm.Show()

    End Sub     

     

    The Delegates Approach

     

    Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type. You can encapsulate any matching method in that delegate. Here we are going to create a delegate with some signature and assign a function to the delegate to assign the text from textbox to label.

     

    Follow the below steps:

     

    Step 1: Add a delegate signature to form1 as below  

     

    Public Delegate Sub delPassData(ByVal text As TextBox)

     

    Step 2: In form1's button click event handler instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below  

     

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles      

        btnSend.Click

        Dim frm As Form2 = New Form2

        Dim del As delPassData = New delPassData(AddressOf frm.funData)

        'Dim del As delPassData = New delPassData(frm.funData)

        del(Me.textBox1)

        frm.Show()

    End Sub

     

    Step 3: In form2, add a function to which the delegate should point to. This function will assign textbox's text to the label.  

     

    Public Sub funData(ByVal text As TextBox)

        label1.Text = text.Text

    End Sub

     

    Conclusion

     

    These four approaches are very simple in implementing data passing between forms. There are also other methods available in accomplishing the same. Source code for the methods I stated above is given at the top for download. It is time for you to put your thinking cap and find other ways of doing this. Happy Coding!!! 

     

    NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/).

    Login to add your contents and source code to this article
    share this article :
    post comment
     

    u r the man !!!

    Posted by Ranga Jul 05, 2011

    I am a C# developer currently being forced to update a VB app. I have a series of forms that can call an advanced search form (ASF) which must be able to cause the calling form to show the record that corresponds to that selected in the ASF while staying open. Your solution for using delegates was so simple that I was easily able to adapt it to suit my needs.

    Posted by Len Flynn May 17, 2011

    The passing of data between forms was great and helped a lot. Can you please give an example of the following The display in form 2 must change in the same window when you change the text in form 1 and click the send button. So there must not pop up a new window just refresh or update the existing window.

    Posted by Arno Pretorius Mar 16, 2011

    your example works great for 1 textbox and 1 label, but what about 2 textboxs and 2 labels on separate forms. would you please show an example on how that works.
    Thanks Steve

    Posted by steve hatcher Sep 26, 2010

    Can data pass into HTML format from sql database table in vbform?


    Posted by Parkash Kaur Dec 19, 2009
    6 Months Free & No Setup Fees ASP.NET Hosting!
    Become a Sponsor
    PREMIUM SPONSORS
    • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
      Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Nevron Diagram
    Become a Sponsor