how can i access a form from another form?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • youngPG
    New Member
    • Feb 2010
    • 1

    how can i access a form from another form?

    i have Form1 then i want to access the datetimepicker in the other form(Form2).. how do i do that? Answers are highly appreciated! thanks!
  • Samishii23
    New Member
    • Sep 2009
    • 246

    #2
    Google is your friend. But this post does provide a simple answer. (I'm learning too. lol)

    .../answers/270705-access-textbox-value-another-form

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      Although you can have Form1 directly access items on Form2 it isn't the recommended way to go. It ties the two forms tightly to each other. If a change is made in Form2 such as removing one of the controls, then code in Form1 breaks.

      It is better to Form1 raise an event, and have Form2 contain its own code for how to react to this. This places responsibility for Form2 within Form2, and Form1 within Form1.

      It keeps Form1 blissfully ignorant of Form2 - and a logging component - and a progress component, and a dozen other little black boxes that can be subscribed to events in Form1, all without Form1 being made responsible for directly affecting controls other than itself.

      Events tutorial (including Form to Form which is the same as class to class)

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        Well, if Form1 is the only one that can spawn Form2, and is in complete control of Form2, then Form1 directly accessing Form2 isn't a big problem. Especially if you are using the ShowDialog method rather than Show.

        What I would do depends on the situation. If Form2 is a Dialog type form, in that when you create it you do something like this:
        Code:
        Form2 f2 = new Form2();
        f2.ShowDialog();
        Then I would just add a public property to Form2. Something like this:
        this is in the class for Form2
        Code:
        public DateTime MyDate
        {
          get { return myDateTimePicker.Value; } //change this to whatever your datetimepicker's name is
        }
        And just grab the value after the dialog is closed.
        this is in Form1 where you spawn the form2
        Code:
        Form2 f2 = new Form2();
        Form2.ShowDialog();
        DateTime value = f2.MyDate;
        If I were using the Show method rather than the ShowDialog method, and I wanted to know every time that Form2's DateTimePicker changed, I would (in form1) handle the form2 instance's ValueChanged event.

        Comment

        Working...