Getting a Return Value from a Form

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • pooba53

    #1

    Getting a Return Value from a Form

    I am working with VB .NET 2003.

    Let's say my main form is called Form1.

    I have to launch a new form (Form2) that gathers input from the user.
    How can I pass variable information back to Form1 before calling the
    Me.close() on Form2?

    -Stumped

  • Earl

    #2
    Re: Getting a Return Value from a Form

    If you call Form2 as a Dialog then the form doesn't go out of scope until
    you Dispose() of it on Form1. So you can set public properties on Form2 and
    reference those from Form1 until such time as you *do* Dispose() of Form2.

    "pooba53" <pooba53@gmail. comwrote in message
    news:1174687928 .834852.10230@l 75g2000hse.goog legroups.com...
    >I am working with VB .NET 2003.
    >
    Let's say my main form is called Form1.
    >
    I have to launch a new form (Form2) that gathers input from the user.
    How can I pass variable information back to Form1 before calling the
    Me.close() on Form2?
    >
    -Stumped
    >

    Comment

    • Herfried K. Wagner [MVP]

      #3
      Re: Getting a Return Value from a Form

      "pooba53" <pooba53@gmail. comschrieb:
      >I am working with VB .NET 2003.
      >
      Let's say my main form is called Form1.
      >
      I have to launch a new form (Form2) that gathers input from the user.
      How can I pass variable information back to Form1 before calling the
      Me.close() on Form2?
      \\\
      Public Class Form2
      Inherits System.Windows. Forms.Form

      #Region " Vom Windows Form Designer generierter Code "
      Public Sub New()
      MyBase.New()
      InitializeCompo nent()
      End Sub

      Protected Overloads Overrides Sub Dispose( _
      ByVal disposing As Boolean _
      )
      If disposing Then
      If Not (components Is Nothing) Then
      components.Disp ose()
      End If
      End If
      MyBase.Dispose( disposing)
      End Sub

      Private components As System.Componen tModel.IContain er

      Friend WithEvents btnCancel As System.Windows. Forms.Button
      Friend WithEvents btnOK As System.Windows. Forms.Button
      Friend WithEvents DateTimePicker1 As System.Windows. Forms.DateTimeP icker

      <System.Diagnos tics.DebuggerSt epThrough()_
      Private Sub InitializeCompo nent()
      Me.btnCancel = New System.Windows. Forms.Button()
      Me.btnOK = New System.Windows. Forms.Button()
      Me.DateTimePick er1 = New System.Windows. Forms.DateTimeP icker()
      Me.SuspendLayou t()
      '
      'btnCancel
      '
      Me.btnCancel.Di alogResult = System.Windows. Forms.DialogRes ult.Cancel
      Me.btnCancel.Fl atStyle = System.Windows. Forms.FlatStyle .System
      Me.btnCancel.Lo cation = New System.Drawing. Point(176, 144)
      Me.btnCancel.Na me = "btnCancel"
      Me.btnCancel.Si ze = New System.Drawing. Size(80, 24)
      Me.btnCancel.Ta bIndex = 0
      Me.btnCancel.Te xt = "Cancel"
      '
      'btnOK
      '
      Me.btnOK.FlatSt yle = System.Windows. Forms.FlatStyle .System
      Me.btnOK.Locati on = New System.Drawing. Point(88, 144)
      Me.btnOK.Name = "btnOK"
      Me.btnOK.Size = New System.Drawing. Size(80, 24)
      Me.btnOK.TabInd ex = 1
      Me.btnOK.Text = "OK"
      '
      'DateTimePicker 1
      '
      Me.DateTimePick er1.Location = New System.Drawing. Point(16, 24)
      Me.DateTimePick er1.Name = "DateTimePicker 1"
      Me.DateTimePick er1.Size = New System.Drawing. Size(240, 20)
      Me.DateTimePick er1.TabIndex = 2
      '
      'Form2
      '
      Me.AcceptButton = Me.btnOK
      Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
      Me.CancelButton = Me.btnCancel
      Me.ClientSize = New System.Drawing. Size(274, 184)
      Me.Controls.Add Range(New System.Windows. Forms.Control() {Me.DateTimePic ker1,
      Me.btnOK, Me.btnCancel})
      Me.FormBorderSt yle = System.Windows. Forms.FormBorde rStyle.FixedDia log
      Me.MaximizeBox = False
      Me.MinimizeBox = False
      Me.Name = "Form2"
      Me.ShowInTaskba r = False
      Me.Text = "Select date"
      Me.ResumeLayout (False)
      End Sub
      #End Region

      Private Sub btnOK_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArg s _
      ) Handles btnOK.Click
      Me.DialogResult = DialogResult.OK
      Me.Close()
      End Sub

      Private Sub btnCancel_Click ( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArg s _
      ) Handles btnCancel.Click
      Me.DialogResult = DialogResult.Ca ncel
      Me.Close()
      End Sub

      Public Property [Date]() As Date
      Get
      Return Me.DateTimePick er1.Value
      End Get
      Set(ByVal Value As Date)
      Me.DateTimePick er1.Value = Value
      End Set
      End Property
      End Class
      ///

      Aufruf:

      \\\
      Private Sub Button1_Click(. ..) ...
      Dim f As New Form2()
      If f.ShowDialog() = DialogResult.OK Then
      MsgBox(f.Date.T oString())
      Else
      MsgBox("Cancell ed")
      End If
      f.Dispose()
      End Sub
      ///


      --
      M S Herfried K. Wagner
      M V P <URL:http://dotnet.mvps.org/>
      V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

      Comment

      • Cor Ligthert [MVP]

        #4
        Re: Getting a Return Value from a Form

        pooba,

        Whatever you do you have to think about friend and public protection.
        I like the friend protection, that allows the use of data inside a project
        (this is of course as long as your solution exist from one project).

        You have only to focus on the class/object from which you want data.

        Therefore as you make in your let say formX a field or better property.

        Friend TheFieldToUseBy OtherForms as String

        You can in most situatisons do

        dim frm as formX
        frm.Show....... ....
        TheInformationI WantFromFormx = frm.TheFieldToU sByOtherForms
        frm.Dispose

        Be aware that there is only one form on a time active, sometimes you want
        this in the situation
        frm1 <-----frm2

        You want to be active in frm2 but show information in frm1. Than you make a
        field in frm1 friend and changes that from frm2.

        I hope this helps,'

        Cor



        "pooba53" <pooba53@gmail. comschreef in bericht
        news:1174687928 .834852.10230@l 75g2000hse.goog legroups.com...
        >I am working with VB .NET 2003.
        >
        Let's say my main form is called Form1.
        >
        I have to launch a new form (Form2) that gathers input from the user.
        How can I pass variable information back to Form1 before calling the
        Me.close() on Form2?
        >
        -Stumped
        >

        Comment

        • Mike Hofer

          #5
          Re: Getting a Return Value from a Form

          On Mar 24, 12:47 am, "Cor Ligthert [MVP]" <notmyfirstn... @planet.nl>
          wrote:
          pooba,
          >
          Whatever you do you have to think about friend and public protection.
          I like the friend protection, that allows the use of data inside a project
          (this is of course as long as your solution exist from one project).
          >
          You have only to focus on the class/object from which you want data.
          >
          Therefore as you make in your let say formX a field or better property.
          >
          Friend TheFieldToUseBy OtherForms as String
          >
          You can in most situatisons do
          >
          dim frm as formX
          frm.Show....... ....
          TheInformationI WantFromFormx = frm.TheFieldToU sByOtherForms
          frm.Dispose
          >
          Be aware that there is only one form on a time active, sometimes you want
          this in the situation
          frm1 <-----frm2
          >
          You want to be active in frm2 but show information in frm1. Than you make a
          field in frm1 friend and changes that from frm2.
          >
          I hope this helps,'
          >
          Cor
          >
          "pooba53" <poob...@gmail. comschreef in berichtnews:117 4687928.834852. 10230@l75g2000h se.googlegroups .com...
          >
          >
          >
          I am working with VB .NET 2003.
          >
          Let's say my main form is called Form1.
          >
          I have to launch a new form (Form2) that gathers input from the user.
          How can I pass variable information back to Form1 before calling the
          Me.close() on Form2?
          >
          -Stumped- Hide quoted text -
          >
          - Show quoted text -
          I'm going to have to throw in a caveat about Friend fields.

          In my thinking, *fields* should *ALWAYS* be private unless you have an
          utterly compelling reason to make them visible outside the class.
          Forms are just classes. Make them private, and create accessor
          properties that other classes use to read them.

          You *never* want to risk someone changing the value of that field
          without your consent. If it's a field, you have no control over when
          it's changed; it's volatile. Trust me--if you dangle it off the form
          as a field, someone, somewhere, WILL change it simply because they
          CAN. There's nothing to prevent them from doing so.

          With a property to wrap it, you get the benefit of control over it's
          value. You can validate it, ensure that it's not null, range-checked,
          valid for the context of the task at hand, and so on. You don't have
          to make the field public; mark it Friend if you want to. In fact, mark
          the entire class Friend if you like. But avoid exposing a field as
          anything but private unless you have an *utterly compelling* reason to
          do so.

          Folks will tell you about things that the compiler will do for you
          automatically; optimizations that will be made and so forth. Do NOT
          let the compiler make those kinds of decisions for you. Make them
          yourself; that way, you KNOW that you have control over the variable's
          value, and you KNOW when you test that piece of code EXACTLY what the
          variable's value is at all times. You'll know where it came from, what
          it is, and that it's valid at any given point in time.

          Sure, it's a little extra coding on your part. But isn't that little
          bit of extra effort upfront worth the sure knowledge during testing
          and debugging later? It's one less thing that you have to doubt when
          you are testing your code. When someone asks you whether or not that
          piece of code works, you can answer them definitively, and there will
          be no doubt, because you'll KNOW. There won't be any chance that an
          external piece of code changed the variable's value.

          If you leave it as an exposed field, have you tested for the condition
          where someone changes it from outside the class? If not, you may be in
          for a nasty surprise when it does happen, and those defects are
          notoriously difficult to track down, because it's pretty darned
          difficult to figure out who changed that value. And once you figure
          out that someone has changed it, how do you gracefully recover from
          that situation? Which party is wrong? Your class? Or the one trying to
          change your class's field? After all, by implication, fields aren't
          read-only unless you've marked them that way--they're read-write:
          they're MEANT to be modified. It's only logical to assume that they
          can be safely changed by the caller.

          But you're trusting that variable to have a known value that doesn't
          change. So PROVE it. Make it private, and control access to it.

          Having said all that, that's just the way I write software. Other
          folks have their ways of doing things, and that works for them. I've
          simply learned over time to never trust a variable if I can't *prove*
          it's authenticity and stability while I've got it. So I lock it down.
          Others may have very good, very sound reasons for doing otherwise. But
          my guess is that those reasons are the exception and not the rule;
          exposing fields to other classes should be done very rarely, and when
          done so, with great care. The reasons for doing so should be
          documented quite clearly. You want to explain how such a change will
          impact the code. I would even suggest that instead of exposing the
          field, you'd still hide the field, and provide wrapper methods that
          allow you to ensure that valid values go into it. You just never know
          what someone's going to put into that variable. It's just not safe to
          assume that someone's going to put the value you need into that
          variable.

          Just a few things to think about.

          Mike


          Comment

          • Rory Becker

            #6
            Re: Getting a Return Value from a Form

            Gotta agree with Mike here.

            Private Fields are the only way to go.

            You're just safer that way.

            The only reason people create non Private fields is that they're too lazy
            to write anything else.

            I am too so I use either snippets(VS2005 ) or Coderush or something else to
            do the (not very) heavy lifting for me.

            It is my belief (as Mike indicates is also his) that non private fields will
            eventually come back and bite you in the ass.

            Just my 2 cents

            Rory


            Comment

            • =?Utf-8?B?aXdkdTE1?=

              #7
              RE: Getting a Return Value from a Form

              what i have done in this situation is just shadow the ShowDialog method and
              return whatever you want

              ::air code::
              Public Function ShowDialog As String

              MyBase.ShowDial og()

              return "Stuff"

              end sub

              hope this helps

              --
              -iwdu15

              Comment

              • Cor Ligthert [MVP]

                #8
                Re: Getting a Return Value from a Form

                Mike,

                I will use a friend property, but for the example it is easier to explain
                and to understand with a field.

                Cor

                "Mike Hofer" <kchighland@gma il.comschreef in bericht
                news:1174751898 .883024.313250@ y80g2000hsf.goo glegroups.com.. .
                On Mar 24, 12:47 am, "Cor Ligthert [MVP]" <notmyfirstn... @planet.nl>
                wrote:
                >pooba,
                >>
                >Whatever you do you have to think about friend and public protection.
                >I like the friend protection, that allows the use of data inside a
                >project
                >(this is of course as long as your solution exist from one project).
                >>
                >You have only to focus on the class/object from which you want data.
                >>
                >Therefore as you make in your let say formX a field or better property.
                >>
                >Friend TheFieldToUseBy OtherForms as String
                >>
                >You can in most situatisons do
                >>
                >dim frm as formX
                >frm.Show...... .....
                >TheInformation IWantFromFormx = frm.TheFieldToU sByOtherForms
                >frm.Dispose
                >>
                >Be aware that there is only one form on a time active, sometimes you want
                >this in the situation
                >frm1 <-----frm2
                >>
                >You want to be active in frm2 but show information in frm1. Than you make
                >a
                >field in frm1 friend and changes that from frm2.
                >>
                >I hope this helps,'
                >>
                >Cor
                >>
                >"pooba53" <poob...@gmail. comschreef in
                >berichtnews:11 74687928.834852 .10230@l75g2000 hse.googlegroup s.com...
                >>
                >>
                >>
                >I am working with VB .NET 2003.
                >>
                Let's say my main form is called Form1.
                >>
                I have to launch a new form (Form2) that gathers input from the user.
                How can I pass variable information back to Form1 before calling the
                Me.close() on Form2?
                >>
                -Stumped- Hide quoted text -
                >>
                >- Show quoted text -
                >
                I'm going to have to throw in a caveat about Friend fields.
                >
                In my thinking, *fields* should *ALWAYS* be private unless you have an
                utterly compelling reason to make them visible outside the class.
                Forms are just classes. Make them private, and create accessor
                properties that other classes use to read them.
                >
                You *never* want to risk someone changing the value of that field
                without your consent. If it's a field, you have no control over when
                it's changed; it's volatile. Trust me--if you dangle it off the form
                as a field, someone, somewhere, WILL change it simply because they
                CAN. There's nothing to prevent them from doing so.
                >
                With a property to wrap it, you get the benefit of control over it's
                value. You can validate it, ensure that it's not null, range-checked,
                valid for the context of the task at hand, and so on. You don't have
                to make the field public; mark it Friend if you want to. In fact, mark
                the entire class Friend if you like. But avoid exposing a field as
                anything but private unless you have an *utterly compelling* reason to
                do so.
                >
                Folks will tell you about things that the compiler will do for you
                automatically; optimizations that will be made and so forth. Do NOT
                let the compiler make those kinds of decisions for you. Make them
                yourself; that way, you KNOW that you have control over the variable's
                value, and you KNOW when you test that piece of code EXACTLY what the
                variable's value is at all times. You'll know where it came from, what
                it is, and that it's valid at any given point in time.
                >
                Sure, it's a little extra coding on your part. But isn't that little
                bit of extra effort upfront worth the sure knowledge during testing
                and debugging later? It's one less thing that you have to doubt when
                you are testing your code. When someone asks you whether or not that
                piece of code works, you can answer them definitively, and there will
                be no doubt, because you'll KNOW. There won't be any chance that an
                external piece of code changed the variable's value.
                >
                If you leave it as an exposed field, have you tested for the condition
                where someone changes it from outside the class? If not, you may be in
                for a nasty surprise when it does happen, and those defects are
                notoriously difficult to track down, because it's pretty darned
                difficult to figure out who changed that value. And once you figure
                out that someone has changed it, how do you gracefully recover from
                that situation? Which party is wrong? Your class? Or the one trying to
                change your class's field? After all, by implication, fields aren't
                read-only unless you've marked them that way--they're read-write:
                they're MEANT to be modified. It's only logical to assume that they
                can be safely changed by the caller.
                >
                But you're trusting that variable to have a known value that doesn't
                change. So PROVE it. Make it private, and control access to it.
                >
                Having said all that, that's just the way I write software. Other
                folks have their ways of doing things, and that works for them. I've
                simply learned over time to never trust a variable if I can't *prove*
                it's authenticity and stability while I've got it. So I lock it down.
                Others may have very good, very sound reasons for doing otherwise. But
                my guess is that those reasons are the exception and not the rule;
                exposing fields to other classes should be done very rarely, and when
                done so, with great care. The reasons for doing so should be
                documented quite clearly. You want to explain how such a change will
                impact the code. I would even suggest that instead of exposing the
                field, you'd still hide the field, and provide wrapper methods that
                allow you to ensure that valid values go into it. You just never know
                what someone's going to put into that variable. It's just not safe to
                assume that someone's going to put the value you need into that
                variable.
                >
                Just a few things to think about.
                >
                Mike
                >
                >

                Comment

                Working...