Gå til innhold

Anbefalte innlegg

Videoannonse
Annonse

Du må ha en referanse til den andre formen.

 

1) via Owner variabelen

 

Form2 f = new Form2();
f.Owner = this;
f.Show();

 

 

2) Via en custom constructor

   
   Form2 f = new Form2(this);

    public partial class Form2 : Form
   {
       public Form1 m_frmMain = null;

       public Form2()
       {
           InitializeComponent();
       }

       public Form2(Form1 frmMain) : this()
       {
           m_frmMain = frmMain;
       }
   }

 

3) Via en property

Form2 f = new Form2();
f.MainForm = this;
f.Show();


public partial class Form2 : Form
   {
       public Form1 m_frmMain = null;

       public Form2()
       {
           InitializeComponent();
       }

       public Form1 MainForm
       {
           get { return m_frmMain; }
           set { m_frmMain = value; }
       }
   }

Endret av alftore
Lenke til kommentar
  • 2 uker senere...
  • 3 uker senere...

Du kan f.eks endre i Program.cs fra

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestApp02 {
   static class Program {
       /// <summary>
       /// The main entry point for the application.
       /// </summary>
       [STAThread]
       static void Main() {
           Application.EnableVisualStyles();
           Application.SetCompatibleTextRenderingDefault(false);
           Application.Run(new Form1());
       }
   }
}

til

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestApp02 {
   static class Program {

       public static Form1 MinForm1 = new Form1();
       public static Form2 MinForm2 = new Form2();

       /// <summary>
       /// The main entry point for the application.
       /// </summary>

       [STAThread]
       static void Main() {
           Application.EnableVisualStyles();
           Application.SetCompatibleTextRenderingDefault(false);
           Application.Run(MinForm1);
       }
   }
}

 

Da kan du hvor som helst i all koden din kalle:

object x = Program.MinForm1.EnVariabel;
object y = Program.MinForm2.EnAnnenVariabel;

 

Altså Form1 og Form2 har du en global instans av som du raskt får tilgang via Program.MinForm1 og Program.MinForm2

 

Skal du derimot åpne flere instanser av Form2 vinduet er de tidligere nevnte løsninger over en bedre måte å gjøre dette på. Da må nemlig Form1 vite nøyaktig hvilket av ørten Form2 vinduer den skal hente info fra.

Endret av wolf5
Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
×
×
  • Opprett ny...