Reputation: 856
I have a main windows form and another form that inherits from it.
The second form needs to access the controls (Buttons, PictureBox, etc.) of the main form. Because it inherits from the main form, the default appearance of the child form is identical to the default appearance of the main form.
How can I overcome this and access the main form's controls at the same time?
I don't want to be forced to change my design again!
Question is solved, Thnx for answers...
Upvotes: 1
Views: 1249
Reputation: 3360
I don't know of any way to change the default property values from a parent form's controls in a child form at design time. You can add code to Form_Load to change the values in the child.
To be clear: although the child form you opened inherits from its opener, they are not the same instance. You will need to pass the main form instance as a parameter to the child form's constructor.
PopupForm myPopupForm = new PopupForm(this);
// PopupForm.cs
public class PopupForm : MainForm {
MainForm _opener;
public PopupForm(MainForm opener) {
_opener = opener;
}
}
Upvotes: 0
Reputation: 812
May be something like following, which decide whether or not to show base control.
public partial class baseForm : Form
{
bool canShowControls;
public baseForm(bool canShowBaseControls)
: this()
{
InitializeComponent();
canShowControls = canShowBaseControls;
}
public baseForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HideControls();
}
void HideControls()
{
this.button1.Visible = canShowBaseControls;
this.txtBox.Text = canShowBaseControls;
}
}
public partial class childForm : baseForm
{
public childForm()
{
InitializeComponent();
}
public childForm(bool canShowBaseControl = true)
: base(canShowBaseControl)
{
}
}
Upvotes: 0
Reputation: 151586
When I inherit the other form from the main form, the appearance of the inhereited one becomes exactly like main form.
How can I overcome this and access the main form's controls at the same time.
Well, simply don't inherit it. How and why did you inherit it? And what do you want to access?
If on Form2
you have the following code:
private Form1 _form1;
public Form2(Form1 form1)
{
this._form1 = form1;
}
public void DoSomethingWithForm1()
{
this._form1.SomeControl.DoSomething();
}
Then in DoSomethingWithForm1
you can call methods and access controls on the other form. This is however not a clever design, you'd rather work with Data Transfer Objects or a kind of FormRepository that contains all your forms and passes data between them, so your forms won't have to know about each other.
Upvotes: 1
Reputation: 1629
You can change access type from 'private' to 'protected'. It can be done both in code and using GUI Designed. In GUI Designer this property called 'Modifiers'
Upvotes: 0
Reputation: 723
Not sure if this is the best way! But couldnt you pass "this" through in the constructor this then allows you to then access the public functions you have inside your form
Upvotes: 1