Passing variables from main form to input form

2019-01-29 07:46发布

问题:

I have a simple question. I have a main form, and then a startup form from where I can select a new 3D model to generate. When selecting a new 3D model from the startup form, I want to check first whether the previous model I worked on has been saved or not. I simply want to pass a boolean value from the main form to the startup form using a delegate, but I can't seem to access the main form or any of its variables. I thought it would be as simple as saying: <code>frmMain myForm = new frmMain();</code>, but typing frmMain doesn't show up anything in intellisense.

Any hints?

回答1:

Add a public property on your main form

public bool IsDirty
{
    get;set;
}

you can then access this.ParentForm.IsDirty in your startup form,

remember to pass a reference to the main form when you show the startup form ... startupForm.showDialog(this);



回答2:

Your main form is not accessible to Startup form.You have to store it to something that is accessible at a point where you want to use it.

You can do it by following way also ( along with other ways :)

// This class is mainly used to transfer values in between different components of the system
    public class CCurrent
    {

        public static Boolean Saved = false;


    }

make sure you put this class in namespace which is accessible to both the forms.

Now In your frmMain form set the value of CCurrent.Saved and access it in your startup form.



回答3:

Here's my suggestion: place a 3DModel object property in your main form:

private Model _model;

Declare your startup form as a Dialog ( like OpenFileDialog) and do something like this:

public void OpenModel()
{
using(var frm=new StartUpForm())
{
if(frm.ShowDialog()==DialogResult.OK))
{
if(_model.IsDirty)
{
if(MessageBox.Show("Model is changed do you want to save it?","",MessageBoxButtons.YesNo")==DialogResult.Yes)
_model.Save();

_model=frm.SelectedModel;
}
}
}


}

your startup form should have a interface like this:

public interface IStartupForm:IDisposable
{
DialogResult ShowDialog(IWin32Window parent);
Model SelectedModel{get;}

}