Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Passing a Method to a second form

Passing a Method to a second form

Scheduled Pinned Locked Moved C#
help
12 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    bwood2020
    wrote on last edited by
    #1

    Hi all, I am having problems passing a method from form 1 to form 2. I have on form 1 a dgv and a button. When the form 1 button is clicked it takes me to form 2. On form 2 I have the same set up, a dgv and a button. However, the button on Form 2, when clicked should call a method from form 1 then closes form 2. When I run the windows form application I get no errors. The method on form 1 that I try to call from form 2 is public. Any help is much appreciated. Thank you! Code: Form 1 public void UpdateGridView()             {                // Method code             } form 2 public void MapFormUpdate_Click(object sender, EventArgs e)             {                   Form1 MainForm = new Form1();                   MainForm.UpdateGridView();                   this.Close();               }

    L D P 3 Replies Last reply
    0
    • B bwood2020

      Hi all, I am having problems passing a method from form 1 to form 2. I have on form 1 a dgv and a button. When the form 1 button is clicked it takes me to form 2. On form 2 I have the same set up, a dgv and a button. However, the button on Form 2, when clicked should call a method from form 1 then closes form 2. When I run the windows form application I get no errors. The method on form 1 that I try to call from form 2 is public. Any help is much appreciated. Thank you! Code: Form 1 public void UpdateGridView()             {                // Method code             } form 2 public void MapFormUpdate_Click(object sender, EventArgs e)             {                   Form1 MainForm = new Form1();                   MainForm.UpdateGridView();                   this.Close();               }

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You made a new form to call a method on and then throw it away. I would advice you not to ask why that does not do what you want, I'm sure several people will laugh at you and/or 1-vote you.

      B 1 Reply Last reply
      0
      • L Lost User

        You made a new form to call a method on and then throw it away. I would advice you not to ask why that does not do what you want, I'm sure several people will laugh at you and/or 1-vote you.

        B Offline
        B Offline
        bwood2020
        wrote on last edited by
        #3

        I tried it without the Form1 MainForm = new Form1(); code but it gives an error NullReferenceException. How can I get around this?

        L 1 Reply Last reply
        0
        • B bwood2020

          Hi all, I am having problems passing a method from form 1 to form 2. I have on form 1 a dgv and a button. When the form 1 button is clicked it takes me to form 2. On form 2 I have the same set up, a dgv and a button. However, the button on Form 2, when clicked should call a method from form 1 then closes form 2. When I run the windows form application I get no errors. The method on form 1 that I try to call from form 2 is public. Any help is much appreciated. Thank you! Code: Form 1 public void UpdateGridView()             {                // Method code             } form 2 public void MapFormUpdate_Click(object sender, EventArgs e)             {                   Form1 MainForm = new Form1();                   MainForm.UpdateGridView();                   this.Close();               }

          D Offline
          D Offline
          DaveyM69
          wrote on last edited by
          #4

          Form1 MainForm = new Form1(); is not going to work as it's a new instance of Form1, not the one that you started with. The recommended way of doing this is to raise a custom event in form2, that Form1 subscribes to, so Form1 calls its own method.

          using System;
          using System.Windows.Forms;

          public partial class Form1 : Form
          {
          public Form1()
          {
          InitializeComponent();
          }

          private void buttonShowForm2\_Click(object sender, EventArgs e)
          {
              Form2 form2 = new Form2();
              form2.DoUpdate += new EventHandler(form2\_DoUpdate);
              form2.Show();
          }
          
          void form2\_DoUpdate(object sender, EventArgs e)
          {
              // Do your thing here
              Console.Write("Update");
          }
          

          }

          using System;
          using System.Windows.Forms;

          public partial class Form2 : Form
          {
          public event EventHandler DoUpdate;

          public Form2()
          {
              InitializeComponent();
          }
          
          void buttonUpdate\_Click(object sender, EventArgs e)
          {
              OnDoUpdate(EventArgs.Empty);
          }
          
          protected virtual void OnDoUpdate(EventArgs e)
          {
              EventHandler eh = DoUpdate;
              if (eh != null)
                  eh(this, e);
              Close();
          }
          

          }

          If you need to pass data along with the event, create your own class derived from EventArgs and pass an instance of that instead of EventArgs.Empty. You will need to change the EventHandler to EventHandler<YourEventArgs> See my Events Made Simple[^] article for more details.

          Dave
          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
          Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
          Why are you using VB6? Do you hate yourself? (Christian Graus)

          B 1 Reply Last reply
          0
          • B bwood2020

            I tried it without the Form1 MainForm = new Form1(); code but it gives an error NullReferenceException. How can I get around this?

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            You want to call it on the original form, not a new one. Usually you only have 1 instance of the main form anyway, so you could use the singleton pattern (makes managers and Java programmers happy) or just pass the instance of form1 to form2 when you make form2. (or use an event, see Davey's post) There is a difference between a class and an instance of it. I'm sure you know, but it seems like you need to be reminded of that. But no offense..

            B 1 Reply Last reply
            0
            • L Lost User

              You want to call it on the original form, not a new one. Usually you only have 1 instance of the main form anyway, so you could use the singleton pattern (makes managers and Java programmers happy) or just pass the instance of form1 to form2 when you make form2. (or use an event, see Davey's post) There is a difference between a class and an instance of it. I'm sure you know, but it seems like you need to be reminded of that. But no offense..

              B Offline
              B Offline
              bwood2020
              wrote on last edited by
              #6

              No offense taken. I'm new to C# programming. Usually work with SQL. Thanks for the input!

              1 Reply Last reply
              0
              • B bwood2020

                Hi all, I am having problems passing a method from form 1 to form 2. I have on form 1 a dgv and a button. When the form 1 button is clicked it takes me to form 2. On form 2 I have the same set up, a dgv and a button. However, the button on Form 2, when clicked should call a method from form 1 then closes form 2. When I run the windows form application I get no errors. The method on form 1 that I try to call from form 2 is public. Any help is much appreciated. Thank you! Code: Form 1 public void UpdateGridView()             {                // Method code             } form 2 public void MapFormUpdate_Click(object sender, EventArgs e)             {                   Form1 MainForm = new Form1();                   MainForm.UpdateGridView();                   this.Close();               }

                P Offline
                P Offline
                Patrik karlin
                wrote on last edited by
                #7

                Hej bwood2020 You Migth whant to use a static resource that can laungh that form1 passes an event to

                static class EventHandler
                {
                static Action Event; // the global state
                public static void SetGlobalEvent(Action a) // Setts the event
                {
                Event = a;
                }
                public static void Execute_Event() // Execute the event
                {
                Event();
                }

                }
                
                class Form1
                {
                    public Form1()
                    {
                        EventHandler.SetGlobalEvent(Event); // Sett the event
                    }
                
                    public void Event() // The events that going to be executet
                    {
                        var x = 2 + 2;
                    }
                }
                
                class Form2
                {
                    public void Onclick()
                    {
                        EventHandler.Execute\_Event(); // Execute the event
                        this.Destroy(); // Destroy your form ( or close )
                    }
                }
                

                There migth be a bether way of doing this if form1 creates form2 you can pass in "this" from form1 as a parameter that way form2 whill be able to call the method on that object Hopes this helps Patrik

                D 1 Reply Last reply
                0
                • P Patrik karlin

                  Hej bwood2020 You Migth whant to use a static resource that can laungh that form1 passes an event to

                  static class EventHandler
                  {
                  static Action Event; // the global state
                  public static void SetGlobalEvent(Action a) // Setts the event
                  {
                  Event = a;
                  }
                  public static void Execute_Event() // Execute the event
                  {
                  Event();
                  }

                  }
                  
                  class Form1
                  {
                      public Form1()
                      {
                          EventHandler.SetGlobalEvent(Event); // Sett the event
                      }
                  
                      public void Event() // The events that going to be executet
                      {
                          var x = 2 + 2;
                      }
                  }
                  
                  class Form2
                  {
                      public void Onclick()
                      {
                          EventHandler.Execute\_Event(); // Execute the event
                          this.Destroy(); // Destroy your form ( or close )
                      }
                  }
                  

                  There migth be a bether way of doing this if form1 creates form2 you can pass in "this" from form1 as a parameter that way form2 whill be able to call the method on that object Hopes this helps Patrik

                  D Offline
                  D Offline
                  DaveyM69
                  wrote on last edited by
                  #8

                  Patrik.karlin wrote:

                  if form1 creates form2 you can pass in "this" from form1 as a parameter

                  ... but now you're starting to couple unrelated classes - not a great idea. The easiest, sure - but best avoided.

                  Dave
                  BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                  Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                  Why are you using VB6? Do you hate yourself? (Christian Graus)

                  P H 2 Replies Last reply
                  0
                  • D DaveyM69

                    Form1 MainForm = new Form1(); is not going to work as it's a new instance of Form1, not the one that you started with. The recommended way of doing this is to raise a custom event in form2, that Form1 subscribes to, so Form1 calls its own method.

                    using System;
                    using System.Windows.Forms;

                    public partial class Form1 : Form
                    {
                    public Form1()
                    {
                    InitializeComponent();
                    }

                    private void buttonShowForm2\_Click(object sender, EventArgs e)
                    {
                        Form2 form2 = new Form2();
                        form2.DoUpdate += new EventHandler(form2\_DoUpdate);
                        form2.Show();
                    }
                    
                    void form2\_DoUpdate(object sender, EventArgs e)
                    {
                        // Do your thing here
                        Console.Write("Update");
                    }
                    

                    }

                    using System;
                    using System.Windows.Forms;

                    public partial class Form2 : Form
                    {
                    public event EventHandler DoUpdate;

                    public Form2()
                    {
                        InitializeComponent();
                    }
                    
                    void buttonUpdate\_Click(object sender, EventArgs e)
                    {
                        OnDoUpdate(EventArgs.Empty);
                    }
                    
                    protected virtual void OnDoUpdate(EventArgs e)
                    {
                        EventHandler eh = DoUpdate;
                        if (eh != null)
                            eh(this, e);
                        Close();
                    }
                    

                    }

                    If you need to pass data along with the event, create your own class derived from EventArgs and pass an instance of that instead of EventArgs.Empty. You will need to change the EventHandler to EventHandler<YourEventArgs> See my Events Made Simple[^] article for more details.

                    Dave
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                    Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                    Why are you using VB6? Do you hate yourself? (Christian Graus)

                    B Offline
                    B Offline
                    bwood2020
                    wrote on last edited by
                    #9

                    Thank you for your reply. That works perfectly.

                    1 Reply Last reply
                    0
                    • D DaveyM69

                      Patrik.karlin wrote:

                      if form1 creates form2 you can pass in "this" from form1 as a parameter

                      ... but now you're starting to couple unrelated classes - not a great idea. The easiest, sure - but best avoided.

                      Dave
                      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                      Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                      Why are you using VB6? Do you hate yourself? (Christian Graus)

                      P Offline
                      P Offline
                      Patrik karlin
                      wrote on last edited by
                      #10

                      DaveyM69 wrote:

                      ... but now you're starting to couple unrelated classes - not a great idea. The easiest, sure - but best avoided.

                      .... Yea Sure .. maybe the logic should be in the model.... form1 can subscribe to a datachanged event and form2 youst update's the data in the model... then they whill be completle seperated.

                      1 Reply Last reply
                      0
                      • D DaveyM69

                        Patrik.karlin wrote:

                        if form1 creates form2 you can pass in "this" from form1 as a parameter

                        ... but now you're starting to couple unrelated classes - not a great idea. The easiest, sure - but best avoided.

                        Dave
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                        Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                        Why are you using VB6? Do you hate yourself? (Christian Graus)

                        H Offline
                        H Offline
                        Henry Minute
                        wrote on last edited by
                        #11

                        Does this look at all familiar? clickety[^] [Edit] Sorry wrong link! Try this one. here[^] [/Edit]

                        Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                        B 1 Reply Last reply
                        0
                        • H Henry Minute

                          Does this look at all familiar? clickety[^] [Edit] Sorry wrong link! Try this one. here[^] [/Edit]

                          Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                          B Offline
                          B Offline
                          bwood2020
                          wrote on last edited by
                          #12

                          Hi Henry, It does and I tried to aply the same logic but it wasn't working. The code I used to get this to work was differnt. I think it had to do with adding another event handler to take care of it.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups