Shaharyar
Shaharyar

Reputation: 12439

derived class has parent private attributes

Got a problem with simple inheritance. The problem is very simple:

I have a Parent Form with name MainForm derived from System.Windows.Forms.Form.

MainForm : System.Windows.Forms.Form

And the second ChildForm is derived from MainForm.

ChildForm : MainForm

MainForm has nothing but a button on it, which is obviously private for this class. The button calls ChildForm.

enter image description here

But after creating ChildForm it also has that button on it, and i can't do any thing with that. It is not even on design panel, but when i run the application, it also works and calls ChildForm. I couldn't figure it out at all...

enter image description here

So how can i remove it from ChildForm and keep it on its place? and why private member is being shown out of its scope?

Upvotes: 1

Views: 154

Answers (2)

slugster
slugster

Reputation: 49974

It's not being shown out of its scope at all. When you create an instance of the ChildForm you also get an instance of the MainForm complete with its bits and pieces - like the button. The 'private' scope simply affects how you can access that button at development time, i.e. you cannot access it programmatically from outside the form's class.

What you need to do is create a public or protected property where you can set the visibility of the button from the child form. In the child form you can toggle (set) that property to the desired default value, a good place for this is in a constructor or form initialisation routine. Depending on which UI technology you are using you can bind the visibility of the button directly to the property, or you can programmaktically set the button's property when the form's property changes.

Upvotes: 2

d h
d h

Reputation: 101

Why does child form need to inherit from main form? From what I understand, Main form has a button which creates a child form instance and displays it. If you end up disabling the only thing on the form there really isn't any point in inheriting from it then...

I would just make ChildForm its own form (inheriting from System.Windows.Forms.Form instead of MainForm), this will remove the button from the ChildForm, and stop you having to make the button on MainForm public/protected.

Upvotes: 0

Related Questions