-2

I have 2 WinForms, in Form1 I declared this:

public int NumberOfContacts { get; set; }

I need to access that property from Form2.

Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
Mike
  • 563
  • 5
  • 15
  • 32
  • 4
    In this case either form1 will need a reference to form2 or vice versa. If one creates the other the natural thing to do is give the created value a reference to the parent from which it can read the necessary values – JaredPar Jan 09 '14 at 14:26
  • You could add a little more detail to the question; does the 2nd form need to be notified when the value changes realtime? If so, you could use an event. If it just needs to pull the value, what @JaredPar suggested will work. – Allan Elder Jan 09 '14 at 14:28

4 Answers4

2

When opening your Form2 use this code:

Form2 f2  = new Form2();
f2.Show(this);

And in your Form2:

var value = ((Form1)Owner).NumberOfContacts;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

If you have created an instance of form2 from form1, you can set it like this:

Form2 form2 = new Form2();
form2.NumberfOfContacts = this.NumberOfContacts;
form2.Show();

You can also pass the value of form1.NumberOfContacts to the constructor of form2 like this:

Form2 form2 = new Form2(this.NumberOfContacts);
form2.Show();

Form2 class:

public int NumberOfContacts { get; set; }

public Form2(int numberOfContacts)
{
    NumberOfContacts = numberOfContacts;
}
Cameron Tinker
  • 9,634
  • 10
  • 46
  • 85
1

If you want to access and change another form properties you can use this way:

private void button1_Click(object sender, EventArgs e)
{
    frm_main frmmain = new frm_main();
    frmmain.Visible = true;
    frmmain.Enabled = true;
}
Milad Rashidi
  • 1,296
  • 4
  • 22
  • 40
hady khann
  • 11
  • 1
0

This is a usual question concerning acceding a Form's member from an other form, I will assume that you want to access NumberOfContacts from the currect active instance of Form1, in that case you would simply , and just as you did declare in your :

Form1 :

 public partial class Form1 : Form
    {
        public int NumberOfContacts { get; set; }
        public Form1()
        {
            InitializeComponent();
        }
    }

and in Form2 :

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            // ActiveForm will give you access to the current opened/activated Form1 instance
            var numberOfContacts  = ((Form1) Form1.ActiveForm).NumberOfContacts;
        }
    }

This should work.

AymenDaoudi
  • 7,811
  • 9
  • 52
  • 84