I have 2 WinForms, in Form1 I declared this:
public int NumberOfContacts { get; set; }
I need to access that property from Form2.
I have 2 WinForms, in Form1 I declared this:
public int NumberOfContacts { get; set; }
I need to access that property from Form2.
When opening your Form2
use this code:
Form2 f2 = new Form2();
f2.Show(this);
And in your Form2:
var value = ((Form1)Owner).NumberOfContacts;
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;
}
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;
}
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.