CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: How to access a class instance from different forms

  1. #1
    Join Date
    Jan 2016
    Posts
    1

    How to access a class instance from different forms

    Hello,

    I have a class:

    Code:
    class Class1
        {
            private string _name;
    
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
    
            private string _lastName;
    
            public string LastName
            {
                get { return _lastName; }
                set { _lastName = value; }
            }
        }
    And I set those variables in Form1:

    Code:
    public partial class Form1 : Form
        {
            Class1 myClass = new Class1();
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                myClass.Name = "John";
                myClass.LastName = "Doe";
    
                Form2 myForm2 = new Form2();
                myForm2.ShowDialog();
            }
        }
    So I want to access this class instance from Form2 and Form3 which is created in Form2. How can I do that?

    I tried something like:
    Code:
    public partial class Form1 : Form
        {
            Class1 myClass = new Class1();
    
            public Class1 sendClass
            {
                get
                {
                    return myClass;
                }
            }
            .
            .
            .
    But I couldn't access it from Form2 and Form3.

    Thanks.

  2. #2
    Join Date
    May 2002
    Posts
    511

    Re: How to access a class instance from different forms

    You can create a second constructor for the Form2 class. Pass Class1 as a parameter into your new constructor.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)