Reputation: 19
I have two forms in a windows form application. lets call them "first form" and "second form". i want by clikcing on a button on second form, change the property of one of the controls of the first form. i've defined an event for this. by that i mean when i click on the second form's button, a method within the first form is called. here's the method:
// changes the visibility of the specified control
public void change_visibility()
{
this.new_customer_label.Visible = true;
}
but when i set a breakpoint on this method and check the value after it is executed. the property has't changed. what is wrong? thanks in advance
note: on the second form button's click event, i also close the form.
Upvotes: 0
Views: 9719
Reputation: 1460
So firstly, Open up Form1.designer.cs
and change the control to public
Form1
this will open Form 2.
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.Show();
Form2
this will change the property of a control in Form 1
(this.Owner as Form1).label1.Visible = true;
Upvotes: 2
Reputation: 2446
As you will search this problem on internet you will find different solutions but I think the best solution is to make controls public then you can access these controls from any form. Follow these instructions.
Form Form2 objForm=new Form2();
objForm.new_customer_label.Visible=true;
I hope this will be helpful to you!!!
Upvotes: 0
Reputation: 1
By default, the designer generates code in the 'Form1.Designer.cs' class. In there, you can see that all the controls are set private, change them to public and then try again...
Upvotes: 0
Reputation: 39152
"note: on the second form button's click event, i also close the form."
Then it would probably be a better design to display the second form with ShowDialog() instead of Show(). Something like:
Form2 f2 = new Form2();
f2.ShowDialog(); // code STOPS here until "f2" is closed
this.new_customer_label.Visible = true;
Upvotes: 0
Reputation: 4455
Here is an example of what you can do:
class Form1 : Form {
private Label labelInForm1;
public string LabelText {
get { return labelInForm1.Text; }
set { labelInForm1.Text = value; }
}
}
class Form2 : Form {
Form1 form1; // Set by the property
private Form1 Form1 {
get { return form1; }
set { form1 = value; }
}
private ChangeVisibility()
{
Form1.labelInForm1.Visible = true;
}
}
Upvotes: 0