Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can declare the object you want to share as a <a href="http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx" rel="nofollow">static</a> field:</p> <pre><code>public partial class Form1 : Form { public static object MyObject; //... } </code></pre> <p>...or declare it as a static property:</p> <pre><code>public partial class Form1 : Form { private static object obj; public static object MyObject { get { return obj; } // read-only } //... } </code></pre> <p>...and then you access it like this (in other classes):</p> <pre><code>object obj = Form1.MyObject; </code></pre> <p>However, if you have multiple instances of Form1, MyObject will be the same for all instances of Form1.</p> <hr> <p>Another approach is setting the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.owner.aspx" rel="nofollow">Form.Owner</a> property, by calling <a href="http://msdn.microsoft.com/en-us/library/szcefbbd.aspx" rel="nofollow">Form.Show()</a>:</p> <pre><code>public partial class Form1 : Form { public object MyObject; // no static required public Form1() { InitializeComponent(); Form2 f2 = new Form2(); f2.Show(this); // this sets the Form.Owner property on f2 } //... } </code></pre> <p>...and then you access it like this (in Form2):</p> <pre><code>Form1 f1 = (Form1)this.Owner; object o = f1.MyObject; </code></pre> <p>The advantage here is that you can now access all public members of Form1, even though they are not declared static. But if you minimize/close Form1, Form2 will also be minimized/closed.</p> <hr> <p>If you don't want to use static or Form.Owner, you can also pass a reference to Form1 instance as a parameter. For example, in Form2 you can write a constructor that takes Form1 as a parameter:</p> <pre><code>public partial class Form2 : Form { public Form2(Form1 f1) { InitializeComponent(); object o = f1.MyObject; // access MyObject like this } //... } </code></pre> <p>...and instantiate Form2 like this (in Form1):</p> <pre><code>Form2 f2 = new Form2(this); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload