简体   繁体   English

如何将值从子表单传递回父表单?

[英]How do I pass a value from a child back to the parent form?

How do I pass a value from a child back to the parent form?如何将值从子表单传递回父表单? I have a string that I would like to pass back to the parent.我有一个字符串,我想传回给父级。

I launched the child using:我使用以下方法启动了孩子:

FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();

Create a property (or method) on FormOptions , say GetMyResult :FormOptions上创建一个属性(或方法),比如GetMyResult

using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string result = formOptions.GetMyResult;

    // do what ever with result...
}

If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go .如果您只是使用 formOptions 选择单个值然后关闭,Mitch 的建议是一个很好的方法 My example here would be used if you needed the child to communicate back to the parent while remaining open.如果您需要孩子在保持开放状态的同时与父母沟通,将使用我的示例。

In your parent form, add a public method that the child form will call, such as在父窗体中,添加子窗体将调用的公共方法,例如

public void NotifyMe(string s)
{
    // Do whatever you need to do with the string
}

Next, when you need to launch the child window from the parent, use this code:接下来,当您需要从父窗口启动子窗口时,请使用以下代码:

using (FormOptions formOptions = new FormOptions())
{
    // passing this in ShowDialog will set the .Owner 
    // property of the child form
    formOptions.ShowDialog(this);
}

In the child form, use this code to pass a value back to the parent:在子窗体中,使用此代码将值传递回父窗体:

ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");

The code in this example would be better used for something like a toolbox window which is intended to float above the main form.此示例中的代码更适合用于工具箱窗口之类的东西,该窗口旨在浮动在主窗体上方。 In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().在这种情况下,您将使用 .Show() 而不是 .ShowDialog() 打开子窗体(使用 .TopMost = true)。

A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method).这样的设计意味着子窗体与父窗体紧密耦合(因为子窗体必须将其所有者强制转换为 ParentForm 才能调用其 NotifyMe 方法)。 However, this is not automatically a bad thing.然而,这并不自然是一件坏事。

You can also create a public property.您还可以创建公共属性。

// Using and namespace...

public partial class FormOptions : Form
{
    private string _MyString;    //  Use this
    public string MyString {     //  in 
      get { return _MyString; }  //  .NET
    }                            //  2.0

    public string MyString { get; } // In .NET 3.0 or newer

    // The rest of the form code
}

Then you can get it with:然后你可以得到它:

FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();

string myString = formOptions.MyString;

You can also create an overload of ShowDialog in your child class that gets an out parameter that returns you the result.您还可以在您的子类中创建 ShowDialog 的重载,以获取返回结果的 out 参数。

public partial class FormOptions : Form
{
  public DialogResult ShowDialog(out string result)
  {
    DialogResult dialogResult = base.ShowDialog();

    result = m_Result;
    return dialogResult;
  }
}

Use public property of child form使用子窗体的公共属性

frmOptions {
     public string Result; }

frmMain {
     frmOptions.ShowDialog(); string r = frmOptions.Result; }

Use events使用事件

frmMain {
     frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);
     frmOptions.ShowDialog(); }

Use public property of main form使用主窗体的公共属性

frmOptions {
     public frmMain MainForm; MainForm.Result = "result"; }

frmMain {
     public string Result;
     frmOptions.MainForm = this;
     frmOptions.ShowDialog();
     string r = this.Result; }

Use object Control.Tag;使用对象 Control.Tag; This is common for all controls public property which can contains a System.Object.这对于可以包含 System.Object 的所有控件公共属性都很常见。 You can hold there string or MyClass or MainForm - anything!您可以将字符串或 MyClass 或 MainForm 放在那里 - 任何东西!

frmOptions {
     this.Tag = "result": }
frmMain {
     frmOptions.ShowDialog();
     string r = frmOptions.Tag as string; }

Well I have just come across the same problem here - maybe a bit different.好吧,我刚刚在这里遇到了同样的问题 - 也许有点不同。 However, I think this is how I solved it:但是,我认为这就是我解决它的方法:

  1. in my parent form I declared the child form without instance eg RefDateSelect myDateFrm;在我的父表单中,我声明了没有实例的子表单,例如RefDateSelect myDateFrm; So this is available to my other methods within this class/ form所以这可用于我在这个类/表单中的其他方法

  2. next, a method displays the child by new instance:接下来,一个方法通过新实例显示子项:

     myDateFrm = new RefDateSelect(); myDateFrm.MdiParent = this; myDateFrm.Show(); myDateFrm.Focus();
  3. my third method (which wants the results from child) can come at any time & simply get results:我的第三种方法(需要孩子的结果)可以随时出现并简单地获得结果:

     PDateEnd = myDateFrm.JustGetDateEnd(); pDateStart = myDateFrm.JustGetDateStart();`

    Note: the child methods JustGetDateStart() are public within CHILD as:注意:子方法JustGetDateStart()在 CHILD 中是公开的:

     public DateTime JustGetDateStart() { return DateTime.Parse(this.dtpStart.EditValue.ToString()); }

I hope this helps.我希望这有帮助。

For Picrofo EDY对于 Picrofo EDY

It depends, if you use the ShowDialog() as a way of showing your form and to close it you use the close button instead of this.Close() .这取决于,如果您使用ShowDialog()作为显示表单的方式并关闭它,您可以使用关闭按钮而不是this.Close() The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone.表单不会被处理或销毁,它只会被隐藏并且在消失后可以进行更改。 In order to properly close it you will need the Dispose() or Close() method.为了正确关闭它,您将需要Dispose()Close()方法。 In the other hand, if you use the Show() method and you close it, the form will be disposed and can not be modified after.另一方面,如果您使用Show()方法并关闭它,则表单将被处理并且之后无法修改。

If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form.如果将子窗体显示为模式对话框,则可以使用 DialogResult 枚举中的值设置子窗体的 DialogResult 属性,该值又会隐藏模式对话框,并将控制权返回给调用窗体。 At this time parent can access child form's data to get the info that it need.此时父表单可以访问子表单的数据以获取所需的信息。

For more info check this link: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx有关更多信息,请查看此链接: http : //msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx

i had same problem i solved it like that , here are newbies step by step instruction我有同样的问题,我是这样解决的,这里是新手一步一步的说明

first create object of child form it top of your form class , then use that object for every operation of child form like showing child form and reading value from it.首先在表单类的顶部创建子表单的对象,然后将该对象用于子表单的每个操作,例如显示子表单和从中读取值。

example例子

namespace ParentChild
{
   // Parent Form Class
    public partial class ParentForm : Form
    {
        // Forms Objects
        ChildForm child_obj = new ChildForm();


        // Show Child Forrm
        private void ShowChildForm_Click(object sender, EventArgs e)
        {
            child_obj.ShowDialog();
        }

       // Read Data from Child Form 
        private void ReadChildFormData_Click(object sender, EventArgs e)
        {
            int ChildData = child_obj.child_value;  // it will have 12345
        }

   }  // parent form class end point


   // Child Form Class
    public partial class ChildForm : Form
    {

        public int child_value = 0;   //  variable where we will store value to be read by parent form  

        // save something into child_value  variable and close child form 
        private void SaveData_Click(object sender, EventArgs e)
        {
            child_value = 12345;   // save 12345 value to variable
            this.Close();  // close child form
        }

   }  // child form class end point


}  // name space end point

When you use the ShowDialog() or Show() method, and then close the form, the form object does not get completely destroyed ( closing != destruction ).当您使用ShowDialog()Show()方法,然后关闭表单时,表单对象不会完全销毁(关闭 != destroy )。 It will remain alive, only it's in a "closed" state, and you can still do things to it.它会保持活动状态,只是处于“关闭”状态,您仍然可以对其进行操作。

Many ways to skin the cat here and @Mitch's suggestion is a good way.在这里给猫剥皮的方法有很多, @Mitch 的建议是一个好方法。 If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.如果您希望客户端表单具有更多的“控制”,您可能希望在创建时将父表单的实例传递给子表单,然后您可以在子表单上调用任何公共父方法。

我认为最简单的方法是在 FormOptions 类中使用 Tag 属性设置需要传递的 Tag = 值,然后在 ShowDialog 方法将其读取为

myvalue x=(myvalue)formoptions.Tag;

The fastest and more flexible way to do that is passing the parent to the children from the constructor as below:最快和更灵活的方法是将父级从构造函数传递给子级,如下所示:

  1. Declare a property in the parent form:在父表单中声明一个属性:

    public string MyProperty {get; set;}

  2. Declare a property from the parent in child form:在子窗体中从父级声明一个属性:

    private ParentForm ParentProperty {get; set;}

  3. Write the child's constructor like this:像这样编写孩子的构造函数:

     public ChildForm(ParentForm parent){ ParentProperty= parent; }
  4. Change the value of the parent property everywhere in the child form:在子窗体中随处更改父属性的值:

    ParentProperty.MyProperty = "New value";

It's done.完成。 the property MyProperty in the parent form is changed.父窗体中的属性MyProperty已更改。 With this solution, you can change multiple properties from the child form.使用此解决方案,您可以从子窗体更改多个属性。 So delicious, no?!太好吃了,不是吗?!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM