none
share class object across the Window Forms RRS feed

  • Question

  • I am new to C# .net.I want to share class object across the Window Forms in my application

    So that if one form update the object it should reflect in other forms

    as i know static class as solution is it the best way to do this...

    Sunday, April 7, 2013 4:18 PM

Answers

  • In a project one for is the main form that gets create when the application starts (usualy form1) and then the 2nd Form gets created in th eFirst form.  I crete a class ""A" and passed an instance of the class to Form2 in the constructor of Form2.  See code below

    Form 1 code

    using System;
    using System.Windows.Forms;
    namespace WindowsFormsApplication1
    {
        public class A
        {
        }
        public partial class Form1 : Form
        {
            Form2 form2;
            public Form1()
            {
                InitializeComponent();
                A a = new A();
                form2 = new Form2(a);
            }
        }
    }

    Form 2 code

    namespace WindowsFormsApplication1
    {
        public partial class Form2 : Form
        {
            A a;
            public Form2(A _a)
            {
                InitializeComponent();
                a = _a;
            }
        }
    }


    jdweng

    Sunday, April 7, 2013 6:05 PM