tags:

views:

47

answers:

2

Hi, I have a simple windows application in C# with 3 forms. first form is main form (its name is FrmMain), second is FrmData and third is FrmShow. In main form (FrmMain) I have created an instance from second form (FrmData) and show it :

    public partial class FrmMain : Form
    {
        public Form FrmModifyData; //for FrmData
        int PersonCode;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnShowDataForm_Click(object sender, EventArgs e)
        {
            FrmModifyData= new FrmData();  
            FrmModifyData.ShowDialog();

        }
    }

but I can't access from FrmModifyData to FrmMain fields like PersonCode . How can I access to creator object's field?

Note: I'm a beginner.

thanks.

A: 

If you want to access PersonCode field, you should declare it as public. No visibility modifier will make it private, hence not accesible from other casses.

Philippe
+2  A: 

You would need to add a property to your FrmModifyData class to take an instance of the FrmMain class. Then you can do this:

FrmModifyData = new FrmData();
FrmModifyData.ParentData = this;
FrmModifyData.ShowDialog();

Then inside FrmModifyData you would have access to the public members of FrmMain. Obviously this is kind of quick and dirty and not very reusable so i would suggest adding more explicit properties to FrmModifyData with only the data you need to use.

Jason Miesionczek
I think there some design pattern to do this, actually. The parent reference should probably be a paramter of the child constructor, calling it like this: "new FrmData(this);"
Philippe
there might be, but in terms of encapsulation, the better route, IMO, is to only provide the data that the control needs. The control most likely does not need access to every public field/method in the parent frame. If the child frame needs to execute methods on the parent frame then those should probably be inside custom events.
Jason Miesionczek